我遇到了处理程序事件的问题。我需要使用一个NSString参数创建处理程序。我试试,但它不起作用。示例代码:
@interface Example : NSObject {
id target;
SEL action;
}
- (id)initWithTarget:(id)targetObject action:(SEL)runAction;
- (void)activate;
@end
@implementation Example
- (id)initWithTarget:(id)targetObject action:(SEL)runAction {
if (self = [super init]) {
target = targetObject;
action = runAction;
}
return self;
}
- (void)activate {
[target performSelector:action withObject:self withObject: @"My Message"];
}
@end
@interface ExampleHandler : NSObject {
}
-(void):init;
-(void)myHandler:(NSString *)str;
@end
@implementation ExampleHandler
-(void)init {
[super init];
Example *ex = [[Example alloc] initWithTarget: self action: @selector(myHandler) ];
}
-(void)myHandler:(NSString *)str {
NSLog(str);
}
@end
我的代码中应该更改哪个处理器包含一个参数?
答案 0 :(得分:2)
方法'myHandler:'接受一个参数,一个字符串。然而在你的例子中,你传递了两个对象,'self'和字符串。你应该改变
[target performSelector:action withObject:self withObject:@"My Message"];
到
[target performSelector:action withObject:@"My Message"];
另一方面,如果您真的想将'self'传递给方法,请将myHandler方法更改为:
-(void)myHandler:(id)example string:(NSString*)str
另外,您的示例应保留'target',除非您保证ExampleHandler不会在Example对象之前取消分配。