當執行下面的塊時。我的friends_dict
NSMutableDictionary值更改爲friend
更改。如果我沒有錯,這是因爲字典中的值的引用傳遞給friend
。如何傳遞值而不是引用並防止字典發生變化。iOS傳遞值而不是引用
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;
}
}
}
列舉它時不要改變數組。 – zaph
傳遞對象的副本。 –