NSMutableArray addObject:不起作用

时间:2014-10-30 11:42:32

标签: objective-c nsmutablearray

我是 objective-C 的新手,我正在尝试将对象添加到实例NSMutableArray变量中。不知何故,对象(项)可以传递到setSubItems方法,但数组_subItems总是返回“nil”。

以下是标头文件

@interface SUKContainer : SUKItem
{
    NSMutableArray *_subItems;
}
-(void)setSubItems:(id)object;
@end

实施

@implementation SUKContainer
-(void)setSubItems:(id)object 
{      
    [_subItems addObject:object];
}
@end

主要

SUKContainer *items = [[SUKContainer alloc] init];      
for (int i = 0; i < 10; i++)
{
    SUKItem *item = [SUKItem randomItem];
    [items setSubItems:item];
}

非常感谢你的帮助!

1 个答案:

答案 0 :(得分:1)

尝试将其更改为以下代码

@interface SUKContainer : SUKItem

// The ivar will be created for you
@property (nonatomic, strong) NSMutableArray *subItems;

// I'd change the name to addSubItem as it makes more sense 
// because you aren't setting subItems you're adding a subItem
-(void)addSubItem:(id)object;
@end

@implementation SUKContainer 

 // No need for a synthesize as one will auto generate in the background    

- (instancetype)init
{
    if (self = [super init]) { 
        // Initialize subItems
        self.subItems = [[NSMutableArray alloc] init];
    }

    return self;
}

- (void)addSubItem:(id)object 
{     
    if (_subItems == nil) {
        // If the array hasn't been initilized then do so now 
        // this would be a fail safe I would probably initialize 
        // in the init.
        _subItems = [[NSMutableArray alloc] init];
    } 

    // Add our object to the array
    [_subItems addObject:object];
}

@end

然后您可以在代码中的其他位置

SUKContainer *items = [[SUKContainer alloc] init];      
for (int i = 0; i < 10; i++) {
    SUKItem *item = [SUKItem randomItem];
    [items setSubItems:item];
}

说实话,虽然你可能只是做下面的事情然后看起来更干净,然后使用另一个名为addSubItem:的方法

SUKContainer *items = [[SUKContainer alloc] init];

// If subItems hasn't been initialized add the below line
// items.subItems = [[NSMutableArray alloc] init];

for (int i = 0; i < 10; i++) {
     [items.subItems addObject:[SUKItem randomItem]];
}