开发者

Event Handler with Parameters

I have problem with handler event. I need create handler with one NSString parameter. I try, but it doesn't work. Sample code:

@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开发者_JAVA技巧 action: @selector(myHandler) ];

}

-(void)myHandler:(NSString *)str {
    NSLog(str);
}

@end

What should I change in my code that I have handler with one parameter?


The method 'myHandler:' takes one argument, a string. Yet in your example, you are passing it two objects, 'self' and the string. You should change

[target performSelector:action withObject:self withObject:@"My Message"];

to

[target performSelector:action withObject:@"My Message"];

If on the other hand, you really want to pass 'self' to the method, change the myHandler method to something like:

-(void)myHandler:(id)example string:(NSString*)str

On a side note, your Example should either retain 'target' unless you have guarantees that the ExampleHandler will not get deallocated before the Example object.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜