2014-01-18 54 views
0

中的選擇器我正在使用下面定義的類來保存選擇器和選擇器。在選擇器的didSelectRow方法中,我想執行選擇器。但是,當我使用選擇器來更改行時,我總是收到「無法識別的選擇器發送到實例」異常。執行存儲在類

我已經嘗試將選擇器的聲明更改爲「SEL * theSelector」,但是這不會帶來任何快樂,因爲performSelector被調用時該選擇器爲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 
} 
+0

它不應該被聲明爲'SEL *'。錯誤消息中無法識別的選擇器是什麼?在伊娃裏還有別的什麼?你爲什麼做這個? (注意,你不需要初始化ivars爲0 - 這是通過'alloc'完成的,而且你的'init'需要'return self'。) –

+0

在行上提出異常: [self performSelector :theSelector onThread:[NSThread currentThread] withObject:self waitUntilDone:YES]; – AndyW

+0

但是錯誤信息的全文是什麼?什麼是無法識別的選擇器本身? –

回答

0

的問題是,你呼籲ClassA選擇,但選擇是方法ClassB

按說[self performSelector:],你基本上說「對當前對象調用此方法」 - 但目前的目標是ClassA類型,theSelectorMethodClassB一部分,而不是。

您還需要傳入對要調用選擇器的對象的引用 - setTarget:或類似內容。然後,在您的performTheSelector方法中,您會改爲執行[objectB performSelector:...]

但是,請看看target-actiondelegation的常見Objective-C設計模式 - 這些在Cocoa中使用非常廣泛,並且都實現了您之後的功能。

+0

是的,這是有道理的,剛剛得到它的工作。謝謝! – AndyW