2010-09-13 29 views
0

我想以一種按下它的方式編程添加一個按鈕,某個對象正在傳遞。我一直在收到「無法識別的選擇器發送」異常。你可以建議什麼是錯的代碼:UIButton與NSInvocation

// allocate the details button's action 
    SEL selector = @selector(showPropertyDetails:forProperty:); 
    NSMethodSignature *signature = [[self class] instanceMethodSignatureForSelector:selector]; 
    NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature]; 
    [invocation setSelector:selector]; 
    //The invocation object must retain its arguments 
    [property retain];  
    //Set the arguments 
    [invocation setTarget:self]; 
    [invocation setArgument:&property atIndex:3];  
    [(UIButton*)[myView viewWithTag:15] addTarget:self action:@selector(selector) forControlEvents:UIControlEventTouchDown]; 

進一步回落,在同一個類中的方法是這樣的:

-(void) showPropertyDetails:(id)something forProperty:(Property *)property { 
int i=0; 
} 

回答

1

,當你建立一個NSInvocation,你不使用它的任何地方 - 你只是將selector設置爲該按鈕的action。預計此選擇器的格式類似於- (void)foo:(id)sender, ...

你可以改爲使用例如字典。標記作爲映射到某個NSInvocation或存儲其他參數的鍵。

+0

所以你的意思是在點擊一個按鈕是發送多個參數的唯一途徑使用集合對象(字典,數組等),因爲他們將始終只有一個參數? – Amarsh 2010-09-13 11:02:18

+0

@Amarsh:我的意思是你不能在這裏使用incovations等,而是必須將信息和關係存儲在其他地方的按鈕。 – 2010-09-13 11:38:50

+0

@George:是的,謝謝。您的評論確實幫助我解決了我的問題。 Thans爲此。 – Amarsh 2010-09-13 23:14:57

1

我以不同的方式解決了這個問題。子類化的UIButton並添加了我需要的所有屬性。這是類的樣子:

@interface RecentSalePropertyDetailsButton : UIButton { 
    Property* property; 
} 
@property (nonatomic, retain) Property* property; 
@end 
@implementation RecentSalePropertyDetailsButton 
@synthesize property; 
- (id) initWithPropertyAs:(Property*)aProperty{ 
    [super init]; 
    self.property = aProperty; 
    return self; 
} 
@end 

然後,再往下,我做了以下內容:

// allocate the details button's action 
    RecentSalePropertyDetailsButton* button = (RecentSalePropertyDetailsButton *)[myView viewWithTag:15]; 
    button.property = property; 
    [button addTarget:self action:@selector(showRecentSalesPropertyDetails:) forControlEvents:UIControlEventTouchDown]; 
0
//make a button 
    UIButton *button = [UIButton buttonWithType:0]; 
//set button size 
    button.frame = CGRectMake(20,219,280,106); 
//give it a color 
    button.backgroundColor = [UIColor clearColor]; 
//add a method 
    [button addTarget:self action:@selector(cancel) forControlEvents:UIControlEventTouchUpInside]; 
//add it to the currentview 
    [self.view addSubview:button];