自定义代表是零

时间:2013-10-21 00:14:00

标签: ios objective-c delegates

出于某种原因,我的自定义委托是零。这是代码:

·H

@protocol AssignmentDelgate <NSObject>

-(void)newAssignment:(AssignmentInfo *)assignment;

@end
@property (nonatomic,weak)id<AssignmentDelgate> otherdelegate;

的.m

- (IBAction)addTheInfo:(id)sender {
    [self.otherdelegate newAssignment:self.assignmentInfo];
    NSLog(@"%@",self.otherdelegate); //Returning nil!
}

另一个VC.h:

@interface AssignmentListViewController : UITableViewController<AssignmentDelgate,UITextFieldDelegate>

@property(strong,nonatomic) AddEditViewController *vc;

@property (strong, nonatomic) NSMutableArray *alist;

另一个VC.m

-(void)newAssignment:(AssignmentInfo *)assignment
{
    [self.alist addObject:assignment];
}
- (void)viewDidLoad
{
    [super viewDidLoad];

    self.vc.otherdelegate = self;
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;

    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}

为什么代表是nil?我重写了应用程序,但它没有任何区别。链接到项目: http://steveedwin.com/AssignmentAppTwo.zip

1 个答案:

答案 0 :(得分:1)

好的,你正在使用segue推送。

您需要将prepareForSegue更改为:

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{

    if ([segue.identifier isEqualToString:@"addAssignment"])
    {
        AddEditViewController *addEditController = segue.destinationViewController;
        [addEditController setOtherdelegate:self];
    }
}

没有必要实例化self.vc,因为故事板正在为你做这件事。

<强>释 由于您正在使用故事板,故事板实际上是实例化您的视图控制器。所以你已经通过按钮从按钮链接打开下一个控制器。

当你点击按钮时,它调用UIViewController的performSegueWithIdentifier:该方法为你创建你的destinationViewController,你可以在prepareForSegue中拦截它。

所以在您的应用程序中发生了什么,您在viewDidLoad期间创建了AddEditViewController并将其保存在内存中,当您点击按钮调出AddEditViewController时,您实际上是通过segues创建了该类的新实例。