我有UITableViewController,它有类似按钮的推文。我正在做的是当点击按钮时,如果成功尝试更新类似的计数+ 1,我做了所有上述方法,除了更新部分。
我得到Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '-[__NSCFDictionary setObject:forKey:]: mutating method sent to immutable object'
错误。
这是我的代码。
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
FeedTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
NSDictionary *feedList = [liveFeeds objectAtIndex:indexPath.row];
//liveFeeds is NSMutableArray
cell.likeCount.text = [feedList objectForKey:@"likes"];
cell.like.tag = indexPath.row;
[cell.like addTarget:self action:@selector(likeClicked:) forControlEvents:UIControlEventTouchUpInside];
}
-(void) likeClicked:(UIButton*)sender{
//Here im using AFNetworking and getting JSON response.
//After that im doing following to update the like
NSMutableDictionary* feedList = [liveFeeds objectAtIndex:sender.tag];
NSString *oldLike = [feedList objectForKey:@"likes"];
int newLike = [oldLike intValue] + 1;
NSString *strFromInt = [NSString stringWithFormat:@"%d",newLike];
NSLog(@"updated like %@",strFromInt); // up to this it works
[feedList setObject:strFromInt forKey:@"likes"]; // in here it get crashe
[self.tableView reloadData];
}
我想做的是。 liveFeeds
数组更新使用Like Like并重新加载表。我做错了吗?或者有什么简单的方法可以做到这一点吗?
答案 0 :(得分:2)
最有可能[liveFeeds objectAtIndex:sender.tag]
是NSDictionary
,而非NSMutableDictionary
。所以你不能改变它的内容。
构建包含[liveFeeds objectAtIndex:sender.tag]
:
NSMutableDictionary* feedlist = [NSMutableDictionary dictionaryWithDictionary:[liveFeeds objectAtIndex:sender.tag]]
答案 1 :(得分:1)
我还没有尝试过,但我想你正试图在NSDictionary上使用NSMutableDictionary方法。 尝试更改:
NSMutableDictionary* feedList = [liveFeeds objectAtIndex:sender.tag];
要:
NSDictionary* dic = [liveFeeds objectAtIndex:sender.tag];
NSMutableDictionary* feedList = [NSMutableDictionary alloc] initWithDictionary:dic]];
答案 2 :(得分:1)
只需创建NSDictionary的可变副本。实际上NSMutableDictionary* feedList = [liveFeeds objectAtIndex:sender.tag]
会返回NSDictionary
。因此,为了使其可编辑,您必须使用mutableCopy
创建另一个可变的副本。 NSMutableDictionary* feedList = [[liveFeeds objectAtIndex:sender.tag]mutableCopy]
-(void) likeClicked:(UIButton*)sender{
//Here im using AFNetworking and getting JSON response.
//After that im doing following to update the like
NSMutableDictionary* feedList = [[liveFeeds objectAtIndex:sender.tag]mutableCopy];
NSString *oldLike = [feedList objectForKey:@"likes"];
int newLike = [oldLike intValue] + 1;
NSString *strFromInt = [NSString stringWithFormat:@"%d",newLike];
NSLog(@"updated like %@",strFromInt); // up to this it works
[feedList setObject:strFromInt forKey:@"likes"]; // in here it get crashe
[self.tableView reloadData];
}