您好我有一个实例变量NSMutable Array。
我宣布它为
@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
有什么想法吗?
谢谢!
答案 0 :(得分: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]);
}
答案 1 :(得分:0)
另一种方法是在头文件中以这种方式声明数组
@interface yourViewController : UIViewController
{
NSMutableArray* list;
}
@end
然后在ViewDidLoad
中list = [[NSMutableArray alloc] init];
其他所有事情都可以像乔丹所说的那样完成。虽然我不确定两种实现之间的性能是否存在差异。