[英]Objective C - Can't change value in NSMutableArray
I can retrieve data I need from API, but then I can't change values of NSMutableArray. 我可以从API检索所需的数据,但是之后我无法更改NSMutableArray的值。 Here's the data I get from API: 这是我从API获得的数据:
{
favorites = (
{
id = 766;
imageUrl = "766.jpg";
name = "Ground Beef 93% Lean 1LB PKG";
price = "5.99";
qty = 5;
sale = "<null>";
switch = 1;
},
{
id = 3270;
imageUrl = "3270.jpg";
name = "Arnold Premium Italian Bread 20oz PKG";
price = "5.39";
qty = 5;
sale = "<null>";
switch = 1;
},...
);
success = true;
}
I declare favorites property in the interface part : 我在界面部分声明收藏夹属性:
@property (nonatomic, retain) NSMutableArray *favorites;
I store the data in NSMutableArray like this : 我将数据存储在NSMutableArray中,如下所示:
NSError *myError = nil;
NSMutableArray *response = [[NSJSONSerialization JSONObjectWithData:self.responseData options:NSJSONReadingMutableLeaves error:&myError] mutableCopy];
Then I store favorite products in another NSMutableArray object : 然后,将喜欢的产品存储在另一个NSMutableArray对象中:
NSString *success = [response valueForKey:@"success"];
if([success isEqualToString:@"true"]) {
self.favorites = [response valueForKey:@"favorites"];
}
With this data I can display all images, prices, etc. in the table. 有了这些数据,我可以在表格中显示所有图像,价格等。 Problem is when I want to update values in self.favorites mutable array: 问题是当我想更新self.favorites可变数组中的值时:
[self.favorites[indexPath.row] setObject:@"0" forKey:@"switch"];
I get this error : -[__NSCFDictionary setObject:forKey:]: mutating method sent to immutable object . 我收到此错误:-[__ NSCFDictionary setObject:forKey:]: 发送给不可变对象的变异方法 。 I even tried to add mutableCopy when assigning array to favorites : 在将数组分配给收藏夹时,我什至尝试添加mutableCopy:
self.favorites = [[response valueForKey:@"favorites"] mutableCopy];
but that did not work either. 但这也不起作用。
You want NSJSONReadingMutableContainers
, not NSJSONReadingMutableLeaves
. 您需要NSJSONReadingMutableContainers
,而不是NSJSONReadingMutableLeaves
。
Using NSJSONReadingMutableLeaves
gives you mutable strings and other mutable objects inside the containers. 使用NSJSONReadingMutableLeaves
在容器内为您提供可变的字符串和其他可变的对象。 Not what you need here. 不是您这里需要的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.