有没有一种干净的方法可以使用指针(ids)作为NSMutableDictionary中的键?

Cha*_*all 5 objective-c nsmutabledictionary ios

我正在使用NSMutableDictionary来存储有效的某些类的描述符,因为我宁愿不浪费将描述符添加到每个类实例的内存,因为只有1000个对象的非常小的子集将具有描述符.

不幸的是,鉴于:

MyClass* p = [MyClass thingy];
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
NSString* description = @"blah"; //does this work? If not I'm just simplifying for this example.
[dict setObject:description forKey:p]; // BZZZZT a copy of p is made using NSCopying

MyClass* found = [dict objectForKey:p]; //returns nil, as p becomes a different copy.
Run Code Online (Sandbox Code Playgroud)

所以这不起作用.

我可以通过传递NSNumber来破解它:

[dict setObject:description forKey:[NSNumber numberWithInt:(int)p]]; // this is cool
Run Code Online (Sandbox Code Playgroud)

但这不仅是丑陋的,而且因为它是非标准的而容易出错.

考虑到这一点,有一个干净的方法来做到这一点?

xen*_*soz 7

NSValue根据NSValue类参考确认NSCopying.因此,您可以使用NSValue的实例作为键.

使用+ valueWithPointer:将指针值包起来.

NSString* foo = @"foo";
id bar = @"bar";

NSMutableDictionary* dict = [[NSMutableDictionary alloc] init];
[dict setObject:@"forKey:foo" forKey:foo];
[dict setObject:@"forKey:bar" forKey:bar];
[dict setObject:@"forKey:[NSValue... foo]" forKey:[NSValue valueWithPointer:foo]];
[dict setObject:@"forKey:[NSValue... bar]" forKey:[NSValue valueWithPointer:bar]];

NSLog(@"%@", [dict objectForKey:foo]); 
NSLog(@"%@", [dict objectForKey:bar]); 
NSLog(@"%@", [dict objectForKey:[NSValue valueWithPointer:foo]]); 
NSLog(@"%@", [dict objectForKey:[NSValue valueWithPointer:bar]]); 
Run Code Online (Sandbox Code Playgroud)

2013-01-24 04:42:14.051 a.out[67640:707] forKey:foo
2013-01-24 04:42:14.052 a.out[67640:707] forKey:bar
2013-01-24 04:42:14.053 a.out[67640:707] forKey:[NSValue... foo]
2013-01-24 04:42:14.053 a.out[67640:707] forKey:[NSValue... bar]
Run Code Online (Sandbox Code Playgroud)

  • 在带有ARC的iOS 6中,为了使用NSValue,我必须这样做:`[NSValue valueWithPointer:(__ bridge const void*)(obj)]`.它不会让我使用该对象而不进行投射. (3认同)
  • 怎么样:@((NSInteger)obj)? (3认同)