Simple copying pointers with Objective C

后端 未结 3 759
忘掉有多难
忘掉有多难 2020-12-07 06:11

I\'m trying to modify the contents of one pointer using another. I want string2 to point to what string1 points to, so that when I modify string2, it modifies string1. How c

3条回答
  •  渐次进展
    2020-12-07 06:42

    As an alternative to Richard J. Ross III's answer, since they're already pointers — buying you a level of indirection — just make sure that you change what's at the address they're pointing to while leaving it at that address. So, e.g.

    NSMutableString *string1 = [[NSMutableString alloc] initWithString:@"hello"];
    NSMutableString *string2 = string1;
    
    [string2 setString:@"changed"];
    
    NSLog(@"string1: %@, string2: %@"); // "string1: changed, string2: changed"
    

    It's not really a workable general solution because it goes too much against the flow of normal Cocoa practices, but understanding what's going on with pointers and how they communicate objects is worthwhile.

提交回复
热议问题