2013-02-20 83 views
1

所以我有一個學生姓名的數組。我正在運行測試數據,所以我正在經歷一個循環分配和初始化每個學生,然後把它扔在stuArr - 如果我NSLog我的Student.h init()方法它會給我我想要的名字,但當我嘗試打電話他們在我的方法之外,我得到空值:Array保持返回空

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    for (int i = 0; i < 5; i++) { 
     stuArr = [stuArr arrayByAddingObject:[[Student alloc] init]]; 
     id test = [stuArr objectAtIndexedSubscript:i]; 
     NSLog(@"%@", [test stuName]); 
    } 
} 

我在這裏失去了一些重要的東西嗎?如果需要,我可以扔在我的Student.m文件,但一切似乎都很好。

+1

也許你忘了alloc + init數組'stuArray'? – 2013-02-20 20:29:29

+0

這不就是它在循環中做什麼?現在我將NSArray作爲一個在.m文件中合成的屬性。 – 2013-02-20 20:30:40

+0

那麼你的學生指定的名字是? – 2013-02-20 20:30:47

回答

5

我猜你應該ALLOC +初始化stuArr此行之前:

stuArr = [stuArr arrayByAddingObject:[[Student alloc] init]]; 

或嘗試做這樣的事情:

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 

    NSMutableArray *mutStudentsArray = [NSMutableArray array]; 

    for (int i = 0; i < 5; i++) 
    { 
     [mutStudentsArray addObject:[[Student alloc] init]]; 
     id test = [mutStudentsArray objectAtIndex:i]; 
     NSLog(@"%@", [test stuName]); 
    } 

    stuArr = [NSArray arrayWithArray:mutStudentsArray]; 
} 
+1

是的,這是錯的。 'stuArr = [[NSArray alloc] init]' – 2013-02-20 20:39:59

+0

@Howdy_McGee,你的意思是[[[NSMutableArray alloc] init]',對吧? – CodaFi 2013-02-20 20:42:57

+0

現在它只是靜態的。我只是使用測試數據,所以我沒有看到需要讓我變化。 – 2013-02-20 20:44:47

1

tikhop是正確的:如果你填寫的陣列for循環你應該在填充它之前初始化NSMutableArray(可變數組,因爲你正在改變循環中的數組)。在循環中用[array addObject:id]將對象添加到數組中。

[array arrayByAddingObject:id]所做的是創建接收數組的副本並將新對象添加到最後。 這意味着使用你需要做類似下面的(沒有多大意義,這樣做在for循環,雖然,但也許有助於理解):

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    NSArray *stuArr = [NSArray alloc] init]; //stuArr can be used now 

    for (int i = 0; i < 5; i++) { 
     //someCopiedArr is some existing array- arrayByAddingObject will copy someArr and add an object 
     stuArr = [someArr arrayByAddingObject:[[Student alloc] init]]; 
     id test = [stuArr objectAtIndexedSubscript:i]; 
     NSLog(@"%@", [test stuName]); 
    } 
} 

到底stuArr將會是someArr的副本,只是將對象添加到最後。