执行存储在类中的选择器

时间:2014-01-18 22:53:10

标签: objective-c selector uipickerview

我正在使用下面定义的类来保存选择器和选择器。在我想要执行选择器的选择器的didSelectRow方法上。但是,当我使用选择器更改行时,我不断收到“无法识别的选择器发送到实例”异常。

我已经尝试将选择器的声明更改为“SEL * theSelector”,但这并没有带来快乐,因为当调用performSelector时,theSelector为NULL。

任何修复/想法将不胜感激。谢谢你提前。

带选择器的类:

@implementation ClassA{
    UIPickerView *thePicker;
    SEL theSelector;
}

-(id)initWithView:(UIView*)theView{
    thePicker = [[UIPickerView alloc] init];
    thePicker.showsSelectionIndicator = YES;
    thePicker.delegate = self;
    thePicker.dataSource = self;
    [theView addSubview:thePicker];

    theSelector = NULL;
}

-(void)setSelector:(SEL)selector{
    theSelector = selector;
}

-(void)performTheSelector{
    if (theSelector != NULL) {
        [self performSelector:theSelector onThread:[NSThread currentThread] withObject:self waitUntilDone:YES];
    }
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:  (NSInteger)component {
    [self performTheSelector];
}

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    return 1;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    return 10;
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
    return @"Some Row";
}

创建ClassA实例并设置选择器的类:

@implementation ClassB{
}

-(void)initWithView:(UIView*)theView{
    ClassA *objectA = [ClassA alloc] initWithView:theView]];
    [objectA setSelector:@selector(theSelectorMethod:)];
}

-(IBAction)theSelectorMethod:(id)sender{
    //do something
}

1 个答案:

答案 0 :(得分:0)

问题是您在ClassA上调用选择器,但选择器是ClassB上的方法。

通过说[self performSelector:],你基本上是说'在当前对象上调用此方法' - 但当前对象的类型为ClassA,而theSelectorMethodClassB的一部分1}}而不是。

您还需要传入对要调用选择器的对象的引用 - setTarget:或类似的东西。然后,在performTheSelector方法中,您将改为[objectB performSelector:...]

但是,看一下target-actiondelegation的常见Objective-C设计模式 - 这些模式在Cocoa中得到了广泛的应用,并且都实现了您所追求的功能。