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

Store Express Session in Cookie

node.js session cookies express session-cookies

I have found various ways to store a session ID in a cookie for expressjs. What I actually want is to store all my session data in a cookie and not have to worry about a server-side session store.

Can Python edit individual list items?

list python-2.7

I wrote a program that selects random words from lists to make a sentence. I want to write grammar rules for this. Right now I am working on plurals.

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.