共享不可变的 NSStrings [英] Sharing immutable NSStrings

查看:50
本文介绍了共享不可变的 NSStrings的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个大约 10k 个字典的列表,每个字典包含大约 50 个键.所有词典的键或多或少都相同.

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

使用 NSDictionary.alloc.initWithContentsOfFile 加载数据.

The data is loaded using NSDictionary.alloc.initWithContentsOfFile.

似乎键对象在不同字典之间重用,因此内存中没有大约 500k 个字符串,每个唯一键只有一个字符串,因此只有几百个.

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.

所以我想知道这是否是 initWithContentsOfFile 方法的预期行为并且我可以依赖它,还是在某些情况下我会为不同字典中的相同键获得不同的字符串对象?

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?

推荐答案

您遇到的是 Objective-C 实现的一个特性.我不知道它是否是 Cocoa 或 Objective-C 独有的.这是内存优化.

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");
}

myString1 和 myString2 都指向同一个内存位置.控制台将打印相同.

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 和 myString2 不会指向同一个内存位置

myString1 and myString2 will NOT point to the same memory location

在这种情况下,控制台会打印 Not the same,然后 String 匹配.使用 == 比较字符串是不安全的.NSString 有一个特殊的方法叫做 isEqualToString: 用于比较.有可能得到相同的字母串"不等于相同的字母串",因为它们占据不同的内存位置.

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.

无论如何,在您的问题中,如果您使用 initWithContentsOfFile 加载字典,则无需担心在多个字典之间共享键值.每个 NSDictionary 都会为每个键添加一个保留,即使它只在内存中一次.您无需担心它会消失.

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.

这篇关于共享不可变的 NSStrings的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆