【问题标题】:Adding NSMutableDictionary to NSMutableArray - iOS, Objective - C将 NSMutableDictionary 添加到 NSMutableArray - iOS,Objective - C
【发布时间】:2015-11-13 11:52:38
【问题描述】:

在 ViewController (A) 中,我创建了如下属性:

@property (strong, nonatomic) NSMutableArray *someList;

在另一个 ViewController (B) 中,NSMutableDictionary 的一个实例被添加到 someList 属性中,但它总是给出 null。请帮忙。 在 B 中,

A = [[A alloc] init];
[A.someList addObject:someInitializedMutableDictionary];

【问题讨论】:

  • 你必须初始化你的someList属性,否则它将永远保持为空

标签: objective-c nsmutablearray nsarray nsdictionary nsmutabledictionary


【解决方案1】:

需要分配someList属性,一般在子类的init方法中完成。但是存在一个问题,即视图控制器的 init 方法通常不在子类中实现,而在 viewDidLoad 中首选执行此类操作。

因此,我建议您创建一个方法来向someList 添加内容,如下所示:

@implementation A
...

- (void)addToSomeList:(id)object
{
    if (!_someList)
        _someList = [NSMutableArray new];
    [_someList addObject:object];
}

这将在需要添加内容时立即分配someList

【讨论】:

【解决方案2】:

someList 是否曾经被初始化?您不能添加到尚不“存在”的东西。

你不得不说:

self.someList = [[NSMutableArray alloc] init];

self 当然只有当你在 ViewController A 中这样做时

【讨论】:

  • 从外部分配属性是一种糟糕的推广模式。
【解决方案3】:

您的方法的基本问题是集合属性不应该是可变的。它有几个问题。所以,首先让我们改变这一点。此外,您必须添加变异方法(mutators)。

@interface MyClass
@property (readonly, nonatomic) NSArray *items;                   // Better naming
-(void)insertObject:(Item*)item inItemsAtIndex:(NSUInteger)index; // See below
@end

这样做有两个“问题”:

  • 如何更改属性?
  • ivar 不也是不可变的吗?

可变ivar

要获得可变 ivar,只需在实现中声明它:

@implementation MyClass
{
  NSMutableArray _items;
}

此 ivar 将被合成属性使用,因为它具有正确的名称和合法类型(属性的子类)。

您可以在对象生命周期的早期初始化该 ivar,即。 e. -init, -viedDidLoad, $whatever。或者您可以在访问器方法中懒惰地执行此操作(例如 trojanfoe 的答案)。

此外,如果您在 .m 文件中添加一个类延续,将属性切换为读/写,则您可以在内部拥有一个 setter。

如果你有一个setter,你应该明确定义有一个可变副本:

-(void)setItems:(NSArray*)items // Arg type from property
{
  _items = [items mutableCopy];
}

变化

您应该实现几种 KVC 方法。你可以找到一个列表here。即:

-(void)insertObject:(Item*)item inItemsAtIndex:(NSUInteger)index
{
  [_items insertObject:item atIndex:index];
}

通常它只是向集合发送一条适当的消息。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多