gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 20:42:05 25 4
gpt4 key购买 nike

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

- (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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com