2013-10-20 95 views
0

嗨我有一個實例變量NSMutable陣列。填充NSMutableArray不工作

我聲明爲這樣

@property (nonatomic, assign) NSMutableArray *list; 

在viewDidLoad中我實例化。

self.list = [NSMutableArray array]; 

我然後進行包括文本字段的文本字符串,並將其添加到陣列中。

NSString * lines = [NSString stringWithFormat:@"%@,%@,%@,%@,%@", [self.crabText text], [self.trawlText text], [self.trapText text], [self.vesselText text], [self.lengthText text]]; 

    [self.list addObject:lines]; 

這是一個函數,它將繼續向文本字段中添加新的值。

int i; 
    int count; 
    for (i = 0, count = [self.list count]; i < count; i = i + 1) 
    { 
     NSString *element = [self.list objectAtIndex:i]; 
     NSLog(@"The element at index %d in the array is: %@", i, element); // just replace the %@ by %d 
    } 

但是顯示陣列的內容,應用程序崩潰時我嘗試打印數組的內容,我得到

EXC_BAD_ACCESS_CODE

任何想法?

謝謝!

回答

3

更換你的聲明是這樣的:

@property (nonatomic, strong) NSMutableArray *list; // strong and not assign 

初始化數組中的viewDidLoad中:

self.list = [NSMutableArray array]; 

,並通過一個加一個你的字符串:

[self.list addObject:self.crabText.text]; 
[self.list addObject:self.trawlText.text]; 
.... 

下一步,修改你的for循環:

for (int i = 0, i < self.list.count, i++) 
{ 
    NSLog(@"The element at index %d in the array is: %@", i, [self.list objectAtIndex:i]); 
} 
+0

更改分配給強做了它。但爲什麼? – user2402616

+2

因爲assign是針對原始變量的。但是,看看這裏瞭解如何使用它http://stackoverflow.com/questions/8927727/objective-c-arc-strong-vs-retain-and-weak-vs-assign –

0

另一種方式做,這將是這種方式聲明數組在你的頭文件

@interface yourViewController : UIViewController 
{ 
    NSMutableArray* list; 
} 
@end 

然後在viewDidLoad中

list = [[NSMutableArray alloc] init]; 

其他一切可以做到的,就像喬丹說。儘管我不確定兩種執行方式之間的性能是否有差異。