【问题标题】:populating NSMutableArray not working填充 NSMutableArray 不起作用
【发布时间】:2013-10-20 15:32:40
【问题描述】:

您好,我有一个实例变量 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

有什么想法吗?

谢谢!

【问题讨论】:

    标签: ios xcode nsstring nsmutablearray


    【解决方案1】:

    像这样替换您的声明:

    @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]);
    }
    

    【讨论】:

    【解决方案2】:

    另一种方法是在头文件中以这种方式声明数组

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

    然后在ViewDidLoad中

    list = [[NSMutableArray alloc] init];
    

    其他一切都可以按照乔丹所说的那样去做。虽然我不确定这两种实现之间是否存在性能差异。

    【讨论】:

      猜你喜欢
      • 2018-01-19
      • 2012-08-02
      • 2014-10-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多