2014-10-30 66 views
-2

我是新来的objective-C,我试图将对象添加到实例NSMutableArray变量。不知何故对象(项目)可以传递到setSubItems方法,但数组_subItems始终返回“nil”。NSMutableArray addObject:不起作用

这里是头文件

@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]; 
} 

太感谢多为你的帮助!

+0

也许你应该实际上创建数组对象。 – 2014-10-30 11:45:37

回答

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]]; 
} 
+0

我认为[[SUKContainer alloc] init]会初始化SUKContainer实例变量,不是吗?并非常感谢你。有用!! – Roy 2014-10-30 11:52:36

+0

只有你自己编写了'init'方法,否则它只会调用super。在代码 – Popeye 2014-10-30 11:54:27

+0

中添加了一个简单的初始化方法但是,如果使用items.subItems,默认情况下点符号不会调用setSubItems方法吗? – Roy 2014-10-30 12:10:47

相关问题