您将不得不扩展 UIBarButtonItem 类。
这是一个创建 RCBarButtonItem 类的示例。我已经使用 initWithTitle 轻松,我相信你可以改变它......
UIBarButtonItem 子类
#import <UIKit/UIKit.h>
@interface RCBarButtonItem : UIBarButtonItem {
id anObject;
}
@property (nonatomic, retain) id anObject;
- (id)initWithTitle:(NSString *)title style:(UIBarButtonItemStyle)style target:(id)target action:(SEL)action withObject:(id)obj;
@end
@implementation RCBarButtonItem
@synthesize anObject;
-(void)dealloc {
[anObject release];
[super dealloc];
}
- (id)initWithTitle:(NSString *)title style:(UIBarButtonItemStyle)style target:(id)target action:(SEL)action withObject:(id)obj {
if (self = [super initWithTitle:title style:style target:target action:action]) {
self.anObject = obj;
}
return self;
}
@end
然后可以像这样实现:
#import "RootViewController.h"
#import "RCBarButtonItem.h"
@implementation RootViewController
- (void)viewDidLoad {
[super viewDidLoad];
RCBarButtonItem *button = [[RCBarButtonItem alloc] initWithTitle:@"Hello"
style:UIBarButtonItemStylePlain
target:self
action:@selector(doSomething:)
withObject:@"Bye"];
self.navigationItem.rightBarButtonItem = button;
}
- (void)doSomething:(id)sender {
NSLog(@"%@", [(RCBarButtonItem *)sender anObject]);
}