Skip to content

Instantly share code, notes, and snippets.

@cdzombak
Created July 17, 2013 20:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cdzombak/6024010 to your computer and use it in GitHub Desktop.
Save cdzombak/6024010 to your computer and use it in GitHub Desktop.
NSString and NSMutableString fun
#import <Foundation/Foundation.h>
int main(int argc, char *argv[]) {
@autoreleasepool {
NSMutableString *a_mutable = [[NSMutableString alloc] initWithString:@"foo"];
NSString *a_cast_immutable = (NSString *)a_mutable;
assert(a_mutable == a_cast_immutable);
NSMutableString *b = [a_cast_immutable mutableCopy];
NSLog(@"original mutable: %p ; %@", a_mutable, a_mutable); // original mutable: 0x7f8eba40a220 ; foo
NSLog(@" immutable: %p ; %@", a_cast_immutable, a_cast_immutable); // immutable: 0x7f8eba40a220 ; foo
NSLog(@" mutable copy: %p ; %@", b, b); // mutable copy: 0x7f8eba40a2b0 ; foo
[a_mutable appendString:@"bar"];
NSLog(@"appended \"bar\".");
assert(a_mutable == a_cast_immutable);
NSLog(@"original mutable: %p ; %@", a_mutable, a_mutable); // original mutable: 0x7f8eba40a220 ; foobar
NSLog(@" immutable: %p ; %@", a_cast_immutable, a_cast_immutable); // immutable: 0x7f8eba40a220 ; foobar
NSLog(@" mutable copy: %p ; %@", b, b); // mutable copy: 0x7f8eba40a2b0 ; foo
}
}

I knew casting an NSMutableString to NSString to make it "immutable" would result in the same pointer, of course; that the compiler and any users of the NSString would see it as immutable, but that underneath it would still be mutable.

First, this test shows that aliasing can be a big problem in this case; that's something we should be cognizant of.

But calling mutableCopy on an NSString that under the hood knows it is already an NSMutableString returns a new NSMutableString instance. This makes sense: this isn't to avoid aliasing issues, but just because we explicitly asked for a copy.

2013-07-17 16:06:59.900 mutablestrings[3138:507] original mutable: 0x7f8eba40a220 ; foo
2013-07-17 16:06:59.902 mutablestrings[3138:507] immutable: 0x7f8eba40a220 ; foo
2013-07-17 16:06:59.902 mutablestrings[3138:507] mutable copy: 0x7f8eba40a2b0 ; foo
2013-07-17 16:06:59.902 mutablestrings[3138:507] appended "bar".
2013-07-17 16:06:59.902 mutablestrings[3138:507] original mutable: 0x7f8eba40a220 ; foobar
2013-07-17 16:06:59.903 mutablestrings[3138:507] immutable: 0x7f8eba40a220 ; foobar
2013-07-17 16:06:59.903 mutablestrings[3138:507] mutable copy: 0x7f8eba40a2b0 ; foo
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment