代表没有被召集

时间:2011-05-09 17:31:51

标签: iphone objective-c ipad delegates delegation

我有一个UITableViewCell的子类,如下所示:

@class MyCell;

@protocol MyCellDelegate

- (void) viewController:(MyCell*)viewCon userId:(NSNumber*)uid andType:(NSString*)type;

@end

@interface MyCell : UITableViewCell <MHLazyTableImageCell>{
    id <MyCellDelegate> delegate;
    NSNumber * mid;
    NSNumber * uid;
}

- (IBAction) star:(id) sender;
- (IBAction) reply:(id) sender;
- (IBAction) message:(id) sender;

- (void) showMenu;

@property (nonatomic, retain) id <ConvoreCellDelegate> delegate;
@property (nonatomic, retain) NSNumber * mid;
@property (nonatomic, retain) NSNumber * uid;

在IBAction中调用委托:

- (IBAction) star:(id) sender
{
    [self.delegate viewController:self userId:mid andType:@"star"];  
}

我有另一个UIVewController如下:

@interface DetailViewController : UIViewController <UIPopoverControllerDelegate, UITableViewDelegate, UITableViewDataSource, UISplitViewControllerDelegate, RKObjectLoaderDelegate, MHLazyTableImagesDelegate, UITextViewDelegate, ConvoreCellDelegate> {
   .......
}

在实施中我把:

- (void) viewController:(MyCell*)viewCon userId:(NSNumber*)uid andType:(NSString*)type
{
    NSLog(@"DELEGATE IS CALLED");
    if ([type isEqualToString:@"star"]){
        NSLog(@"Message id is %@", uid);
    } else if ([type isEqualToString:@"reply"]){
        [message becomeFirstResponder];
        message.text = @"@username";
    } else if ([type isEqualToString:@"message"]){

    }
}

然而,它并没有进入这个。它从不打印DELEGATE IS CALLED。这是为什么?

1 个答案:

答案 0 :(得分:3)

您是否在创建MyCell后实际设置了委托?

检查的简便方法是添加断点并查看委托引用是否为nil(0x0)。

编辑:根据您的评论,请确保您永远不会设置代理。

创建单元格时,必须将委托对象传递给该单元格,以便调用它。否则,您只是向nil对象发送消息。

因此,假设您正在表视图控制器中正常创建单元格:

MyCell *cell = (MyCell *)[tableView dequeueReusableCellWithIdentifier:@"CellID"];
    if (cell == nil) {
        NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"MyCell" owner:self options:nil];
        cell = [topLevelObjects objectAtIndex:0];
        cell.delegate = self; // <-------- set the delegate after creation
    } else {
        NSLog(@"cached cell");
    }

   //Do you other cell stuff, setting mid and uid for example.