【问题标题】:Add object to NSMutableArray from other class从其他类将对象添加到 NSMutableArray
【发布时间】:2011-05-18 04:22:34
【问题描述】:

我有一个名为PresidentsViewController 的视图控制器类,它在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];

【问题讨论】:

  • 您可以在初始化可变数组并设置其属性的位置发布代码吗?
  • 我刚刚编辑了问题以包含它。

标签: objective-c ios uitableview nsmutablearray


【解决方案1】:

以这种方式添加指向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 也可以。

【讨论】:

  • 感谢您的回复——请参阅我对如何初始化 PresidentAddController 的编辑。是的,你的第一个问题。
  • 根据您的说明更新了答案:)
  • 这行得通!你介意解释一下childController.listController = self; 的作用吗?这似乎是我需要的代码行。此外,对于@property 声明,是否有必要将其设为“assign”,因为您要将其设置为“self”?
【解决方案2】:

我的怀疑是您有一个定义为@property (nonatomic,copy) NSMutableArray *list; 的属性,您是否正在尝试将对象添加到数组中?如果是这样,很可能是因为复制修饰符正在返回数组的不可变副本。尝试创建一个方法来获取对象并将其添加到列表中,而不使用self.list ...只需[list addObject],如果可行,那么这就是你的问题。

【讨论】:

  • 不,我没有遇到异常。我相信首先访问类 PresidentsViewController 是个问题,但我不确定。什么是设置引用/实例的正确方法而不必再次分配/初始化 PresidentsViewController 因为那不起作用?
猜你喜欢
  • 2020-12-18
  • 1970-01-01
  • 1970-01-01
  • 2012-05-29
  • 2012-01-25
  • 1970-01-01
  • 1970-01-01
  • 2011-08-22
  • 1970-01-01
相关资源
最近更新 更多