Add object to NSMutableArray from other class

前端 未结 2 429
一个人的身影
一个人的身影 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.

    0 讨论(0)
  • 2021-01-23 13:21

    My suspicion here would be that you have a property defined as @property (nonatomic,copy) NSMutableArray *list; Are you getting and exception trying to add the object into the array? If so, it's likely because the copy modifier is returning an immutable copy of the array. Try to create a method that takes the object and adds it to the list without using self.list ... just [list addObject] and if that works then this is your problem.

    0 讨论(0)
提交回复
热议问题