Nerd Post: Why do different Cocoa objects have the same address?

I ran across what to me was not a seemingly obvious Cocoa artifact today. Let’s suppose that you create some strings much in the way I do below:NSString *myString1 = @"Kevin";NSString *myString2 = [[myString1 copy] autorelease];NSString *myString3 = [[[NSString alloc] initWithString:myString2] autorelease];NSLog(@"%p, %p, %p", myString1, myString2, myString3);Strangely, my log prints the following:0×6060, 0×6060, 0×6060meaning that all the objects are in the same address space! I didn’t quite understand how this could be considering the fact that I used three different methods to create a string. I tried the same thing with NSArray, NSIndexPath, and some others. Strange…After asking around, I finally got my response from Michael, a Cocoa veteran down the hall. He said, “try the same thing, but with mutable strings.”NSMutableString *myString1 = @"Kevin";NSMutableString *myString2 = [[myString1 copy] autorelease];NSMutableString *myString3 = [NSMutableString stringWithString:myString2];NSLog(@"%p, %p, %p", myString1, myString2, myString3);And sure enough:0xae60dd, 0xae60f7, 0xae60fd: different objects!So what’s the deal behind this? In Cocoa, when you allocated a new immutable string using any method, it checks to see if that string already exists in memory. If so, instead of actually allocating a new string, it just increments its retain count. You can imagine how handy that when you create 60,000 of the same string, and Cocoa just creates one with a retain count of 60,000.With mutable objects, however, we do not just bump the retain count because of the fact that if two sources create the mutable string “Kevin”, for example, and then one of the sources changes it to “Keeven”, they change in both places. Not a good thing. So mutable objects are actually allocated each time you create one.So watch out when you are doing pointer checking with immutable objects. You might not be getting exactly what you thought!

2 Responses to “Nerd Post: Why do different Cocoa objects have the same address?”


  1. 1 Sarah

    i totally agree!!!!!!!

  2. 2 UPC Tech Blog

    I love the preface, “Nerd Post” - can I steal it? Although I’ve never used cocoa I still found this post interesting - that either says something about your ability as a writer or me as a reader, or both - either way, I’ll be checking back with your blog.

Leave a Reply

You must login to post a comment.