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

아마도 실제로 배열을 만들어야합니다. 개체. –

답변

1

방금 ​​아래 할 아마 수 있지만

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

이 정직하게 할 수있는 다른 곳 코드에서

@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 

다음 코드로 변경 시도하고 그 다음에 청소기 보인다 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

+0

'init' 메소드를 작성했다면, super 만 호출하게됩니다. 간단한 초기화 메소드를 코드에 추가했습니다 – Popeye

+0

하지만 items.subItems를 사용하면 점 표기법이 setSubItems 메소드를 기본적으로 호출하지 않습니까? – Roy

관련 문제