iOS传递值而不是引用

时间:2014-05-20 21:23:40

标签: ios nsmutablearray nsmutabledictionary pass-by-value

执行以下块时。我的friends_dict NSMutableDictionary值会随着friend更改而更改。如果我没有错,这是因为字典中值的引用传递给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;
            }
        }
    }

1 个答案:

答案 0 :(得分:0)

复制数组并传入副本。

NSArray *friendList = [friends_dict valueForKey:selectedFriendId];
NSMutableArray *friendsArray = [friendList mutableCopy];