iphone - 无法将对象添加到返回 nil 的可变数组

标签 iphone objective-c xcode nsmutablearray

我正在开发一个应用程序,但无法获取可变数组来接受对象。我尝试设置断点来查看发生了什么,但它一直说可变数组为零。有人有答案吗? 我的代码:

- (void)save:(id) sender {

    // All the values about the product
    NSString *product = self.productTextField.text;
    NSString *partNumber = self.partNumberTextField.text;
    NSString *price = self.priceTextField.text;
    NSString *quantity = self.quantityTextField.text;
    NSString *weigh = self.weighTextField.text;
    NSString *file = [self filePath];

    //Singleton class object
    Object *newObject = [[Object alloc] init];
    newObject.product = product;
    newObject.partNumber = partNumber;
    newObject.price = price;
    newObject.quantity = quantity;
    newObject.weigh = weigh;

    //Array declaration
    mutableArray = [[NSMutableArray alloc]initWithContentsOfFile: file];
    [mutableArray addObject:newObject];
    [mutableArray writeToFile:file atomically:YES];

 }

最佳答案

虽然 initWithContentsOfFile: 可以在 NSMutableArray 上调用,但它是从 NSArray 继承的。返回值是一个不可变的 NSArray。如果您想将对象添加到可变数组中,则必须执行以下操作:

mutableArray = [[[NSMutableArray alloc] initWithContentsOfFile: file] mutableCopy];
[mutableArray addObject:newObject];
[mutableArray writeToFile:file atomically:YES];

现在,addObject: 调用应该可以工作了。

致以诚挚的问候。

关于iphone - 无法将对象添加到返回 nil 的可变数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12540061/

相关文章:

iphone - iPhone/iPod touch/iPad 上的标准 c 库头文件

iphone - 在 iPhone 上启用/禁用每个 View 的状态栏(20 像素问题)

objective-c - 如何在调试配置中启用 ARC 优化器?

iphone - 对于 Iphone,如何从当前加载的 View 引用 Root View Controller ,以便可以替换/切换 View

单击图像时 IOS segue 不起作用

ios - OSStatus 错误 -67028 构建 Ad Hoc iOS 应用程序时

xcode - 本地化 - 向 localizable.strings 文件添加其他语言

iphone - 我可以更新特定用户的应用程序吗?

iphone - 如何构建 OpenSSL 并优化它的可执行文件大小?

ios - 在 Xcode 中更改项目名称导致命名错误