objective-c - 从其他类添加对象到 NSMutableArray

标签 objective-c ios uitableview nsmutablearray

我有一个名为 PresidentsViewController 的 View Controller 类,它在 UITableView 中设置数据。此数据采用 NSMutableArray 的形式,称为 list。我有另一个类 PresidentAddController,它应该根据用户输入的有关总统的数据处理将 President 类型的对象添加到此列表。但是,我无法将对象添加到列表中。我已经确认正确收集了用户为新总统输入的数据,因此它被添加到另一个导致问题的类的列表中。我相信将对象添加到列表的正确代码是:

[pvc.list addObject:newPresident];

但是,我不知道如何正确创建引用/实例/? (这就是 pvc)到 PresidentAddController 内部的 PresidentsViewController,这样我就可以正确地将新总统添加到列表中。我没有为此使用 Interface Builder,因为它只是一个 UITableView。

在这种情况下,如何将总裁添加到列表中?

编辑:数组的初始化方式如下:

@property (nonatomic, retain) NSMutableArray *list;

下面是 PresidentsViewController 中 PresidentAddController 的设置方式:

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

最佳答案

以这种方式添加指向 PresidentAddController 的指针:

// in @interface
PresidentsViewController *listController;

@property (nonatomic, assign) PresidentsViewController *listController;

// in @implementation
@synthesize listController;

然后当您实例化您的 PresidentAddController 时,设置指针:

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

然后你可以在 PresidentAddController 中访问 [listController.list addObject:newPresident];

编辑 childController.listController = self 调用[childController setListController:self],后者又读取@synthesized 方法,并将指针 *listController 设置为指向当前类(如果您在 PresidentsViewController 类中编写代码,则 self 将成为 PresidentsViewController 的当前实例)。

我之所以使用 assign 是因为如果你要使用 retain,那么当你将 listController 设置为 self 它实际上将保留对该对象的拥有引用。如果您尝试解除分配 PresidentsViewController,这可能会导致各种问题,因为如果您在 PresidentAddController 中有一个拥有引用,那么它不会解除分配,直到该引用也被释放。使用 assign 可确保如果您在 PresidentAddController 消失之前释放了 PresidentsViewController,它将被正确释放。当然,也许你想在那种情况下保留它,在这种情况下,在这里使用 retain 也是可以的。

关于objective-c - 从其他类添加对象到 NSMutableArray,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6039841/

相关文章:

objective-c - 尴尬的 arc4random 结果

javascript - iOS 11 - 独立的网络应用程序链接打开默认反转? (处理 Web 应用程序中的 PDF 显示。)

android - 打开特定应用的权限设置 flutter ?

ios - UITableViewCell 约束错误

ios - 为什么每当我使用 Search Display Controller 时底层的 UIViewTable 都会显示

ios - 如何在 UITableView 上添加额外的行分隔符

objective-c - iOS readonly 和 retain 是互斥的

ios - 关于 UIButton 的 titleLabel 和 imageView 属性的困惑

ios - 应用程序在NSUserDefault数据删除期间崩溃

ios - Webview didFailLoadWithError 错误代码 -999