objective-c - [NSString hash] 每次都计算吗?

标签 objective-c cocoa

如果我有一个不可变的字符串,哈希算法是在我每次调用 hash 时运行,还是它会记住该值(假定字符串不能更改)?

最佳答案

重新计算。

-[NSString hash] 实际上是对 -[NSCFString hash] 的调用(由于免费桥接)。

如果你创建一个程序,在同一个字符串上调用 -[NSString hash] 并且你在调用之间中断并改变备份字符串的内存,你会得到一个重新计算的哈希值。这告诉我不涉及缓存。

(gdb) b -[NSCFString hash]
Breakpoint 1 at 0x3b02fa3
(gdb) r
Breakpoint 1, 0x93652fa3 in -[NSCFString hash] ()
(gdb) c
Continuing.
2009-05-13 14:23:39.003 a.out[1754:813] Hash: -327163326

记下哈希值。

Breakpoint 1, 0x93652fa3 in -[NSCFString hash] ()
(gdb) bt          
#0  0x93652fa3 in -[NSCFString hash] ()
#1  0x00001f73 in main () at test.m:10
(gdb) fra 1
#1  0x00001f73 in main () at test.m:10
10      NSLog(@"Hash: %d", [m hash]);
(gdb) info locals
pool = (NSAutoreleasePool *) 0x109760
m = (NSString *) 0x2030
(gdb) x/20x 0x2030
0x2030 <dyld__mach_header+32>:  0xa06f54a0  0x000007c8  0x00001fa2  0x00000012

0xa06f54a0 是“isa”指针,0x00001fa2 是指向“XXXXXX”字符串的指针。

(gdb) set {int}0x1fa2 = 0x59595959

将“XXXXXX”字符串更改为“YYYYXXXX”,然后继续第二次哈希调用

(gdb) c
Continuing.
2009-05-13 14:24:35.884 a.out[1754:813] Hash: -246144954

注意 ObjC 所知道的不可变字符串中不同的哈希值。

我调试(调试)的程序是:

#import <Cocoa/Cocoa.h>

int main()
{
    NSAutoreleasePool * pool = [NSAutoreleasePool new];

    NSString * m = [NSString stringWithString:@"XXXXXXXXXXXXXXXXXX"];

    NSLog(@"Hash: %d", [m hash]);
    NSLog(@"Hash: %d", [m hash]);

    [pool release];
}

关于objective-c - [NSString hash] 每次都计算吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/856764/

相关文章:

ios - 如何在键盘长按上显示一个额外的字符

objective-c - NSError 本身会做什么(如果有的话)?

objective-c - 图形图像保存在文本编辑器中?

objective-c - WebView打开 '_blank'链接

cocoa - 在 Mac 上使用 Alamofire 下载图像并保存到应用程序支持

cocoa - OSX cocoa : How to check which window is in focus?

ios - 标签栏 Controller : Orienting views in different orientations

objective-c - Objc to swift bridge `use of undeclared identifier ' cocoarr'`

ios - Objective C - 动态编译或不编译类和代码

swift - 存档的应用程序不显示窗口内容,在 Xcode 上运行时工作正常