问题
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