Sharing immutable NSStrings

I have a list of about 10k dictionaries, each dictionary contains about 50 keys. Keys are more or less the same for all dictionaries.

The data is loaded using NSDictionary.alloc.initWithContentsOfFile.

It seems that the key objects are reused between different dictionaries, and thus instead of having about 500k strings in memory, I have only one string per unique key, thus just a couple hundreds of them.

So I wonder if it is an expected behavior of initWithContentsOfFile method and I can rely on it, or are there some circumstances when I will get different string objects for the same keys in different dictionaries?

Answers


What you're experiencing is a feature of the Objective-C implementation. I don't know if it's exclusive to Cocoa or Objective-C in general. It's a memory optimization.

NSString *myString1 = @"Hello!";
NSString *myString2 = @"Hello!";
if (myString1 == myString2) {
   NSLog(@"Same");
}

Both myString1 and myString2 will point to the same memory location. The console will print Same.

NSString *myString1 = [[NSString alloc] initWithString:@"Hello!"];
NSString *myString2 = [[NSString alloc] initWithString:@"Hello!"];
if (myString1 == myString2) {
   NSLog(@"Same");
} else {
   NSLog(@"Not the same");
}
if ([myString1 isEqualToString:myString2]) {
   NSLog(@"String matches");
}

myString1 and myString2 will NOT point to the same memory location

IN this case, the console will print Not the same, and then String matches. It's not safe to compare strings by using ==. NSString has a special method called isEqualToString: for comparing. It IS possible to get the same "string of letters" to not be equal to the same "string of letters" because they occupy different memory locations.

Anyway, in your question, you if you're using initWithContentsOfFile to load a dictionary, you don't need to worry about having key values shared across several dictionaries. Each NSDictionary will add a retain to each key, even though it's only in memory once. YOu don't need to worry about it disappearing.


Need Your Help

In C++ I'm getting an error when using a queue and libcurl

c++ http web-crawler libcurl

I'm using C++ and libcurl to make a Web Spider. I'm running into a issue where I get a error saying HTTP is not supported when I use the queue to get the URL. Th error is: http://google.com* Prot...

How does Apache HttpClient's support of cookies work?

cookies httpclient

Does Apache HttpClient support cookies coded in javascript in a site's html or just those sent by the server through http?

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.