Sharing immutable NSStrings

一个人想着一个人 提交于 2020-01-06 12:36:56

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/12322478/sharing-immutable-nsstrings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!