Add object to NSMutableArray from other class

前端 未结 2 430
一个人的身影
一个人的身影 2021-01-23 12:36

I have a view controller class called PresidentsViewController that sets up data in a UITableView. This data is in the form of NSMutableArray

2条回答
  •  执笔经年
    2021-01-23 13:14

    Add a pointer to PresidentAddController this way:

    // in @interface
    PresidentsViewController *listController;
    
    @property (nonatomic, assign) PresidentsViewController *listController;
    
    // in @implementation
    @synthesize listController;
    

    Then when you instantiate your PresidentAddController, set the pointer:

    PresidentAddController *childController = 
      [[PresidentAddController alloc]
       initWithStyle:UITableViewStyleGrouped];
    childController.title = @"Add President";
    childController.listController = self;
    [self.navigationController pushViewController:childController animated:YES];
    [childController release];
    

    So then you can go [listController.list addObject:newPresident]; in PresidentAddController.

    EDIT: childController.listController = self calls [childController setListController:self], which in turn reads the @synthesized method in your implementation and sets the pointer *listController to point to the current class (if you're writing code in the PresidentsViewController class, then self is going to be the current instance of PresidentsViewController).

    The reason why I use assign is because if you were to use retain, then when you set listController to self it will actually keep an owning reference to the object. This can cause all sorts of problems if you ever try to deallocate PresidentsViewController, because if you have an owning reference in PresidentAddController then it will not deallocate until that reference is also released. Using assign ensures that if you ever release the PresidentsViewController before PresidentAddController disappears, it will be properly deallocated. Of course, maybe you want to keep it around in that situation, in which case using retain here is also fine.

提交回复
热议问题