2014-10-30 71 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

相關問題