iOS传递值而不是引用
当执行下面的块时。MyiOS传递值而不是引用,ios,nsmutablearray,nsmutabledictionary,pass-by-value,Ios,Nsmutablearray,Nsmutabledictionary,Pass By Value,当执行下面的块时。Myfriends\u dictNSMutableDictionary值随friend的变化而变化。如果我没有错的话,这是因为字典中的值的引用被传递给了朋友。如何传递值而不是引用并防止字典更改 NSMutableArray *friendsArray = [[NSMutableArray alloc] initWithArray:[friends_dict valueForKey:selectedFriendId]]; for (NSObject *object in [res
friends\u dict
NSMutableDictionary值随friend
的变化而变化。如果我没有错的话,这是因为字典中的值的引用被传递给了朋友
。如何传递值而不是引用并防止字典更改
NSMutableArray *friendsArray = [[NSMutableArray alloc] initWithArray:[friends_dict valueForKey:selectedFriendId]];
for (NSObject *object in [response objectForKey:@"friend_nearby"]){
NSString *id = [NSString stringWithFormat:@"%@",[object valueForKey:@"id"]];
NSString *spotValue = [NSString stringWithFormat:@"%@",[object valueForKey:@"spot"]];
for(int i = 0; i < [friendsArray count]; i++){
FriendDataModel *friend = [[FriendDataModel alloc] init];
friend = [friendsArray objectAtIndex:i];
if ([friend.friendId isEqualToString:id] && ![friend.spot isEqualToString:spotValue] ) {
friend.spot = spotValue; //This is where the dictionary value changes
[friendsArray replaceObjectAtIndex:i withObject:friend];
spotChanged = YES;
}
}
}
NSMutableArray*friendsArray=[[NSMutableArray alloc]initWithArray:[friends\u dict valueForKey:selectedfriendsid]];
对于(NSObject*对象在[response objectForKey:@“friend_Nearest”]中){
NSString*id=[NSString stringWithFormat:@“%@,[object valueForKey:@“id”];
NSString*spotValue=[NSString stringWithFormat:@“%@,[object valueForKey:@“spot”];
对于(int i=0;i<[friendsArray count];i++){
FriendDataModel*friend=[[FriendDataModel alloc]init];
friend=[friendsArray对象索引:i];
if([friend.friendId IsequalString:id]&&&![friend.spot IsequalString:spotValue]){
friend.spot=spotValue;//这是字典值更改的地方
[friendsArray replaceObjectAtIndex:i with object:friend];
spotChanged=是;
}
}
}
复制数组并传入副本
NSArray *friendList = [friends_dict valueForKey:selectedFriendId];
NSMutableArray *friendsArray = [friendList mutableCopy];
在枚举数组时不要对其进行变异。传递对象的副本。在“它不起作用”注释之前,您需要制作
FriendDataModel
,以符合NSCopying
@a-Live感谢提醒!我正在做;)@Zaph我很确定他需要一个深度的。除此之外,我还改变了friend=[friendsArray objectAtIndex:I]
tofriend=[[friendsArray objectAtIndex:i]复制]代码>成功了@A-Live是的,对于OP正在做的事情,看起来她需要一份深度拷贝。