我一直使用帶字符串作爲鍵的NSDictionaries,以及幾乎所有Web/books/etc上的例子。是相同的。我想我會用一個自定義對象來爲它試一試。我落實「copyWithZone」方法來讀取並創建下列基本類:Objective-C:使用自定義對象鍵從NSMutableDictionary獲取值
@interface CustomClass : NSObject
{
NSString *constString;
}
@property (nonatomic, strong, readonly) NSString *constString;
- (id)copyWithZone:(NSZone *)zone;
@end
@implementation CustomClass
@synthesize constString;
- (id)init
{
self = [super init];
if (self) {
constString = @"THIS IS A STRING";
}
return self;
}
- (id)copyWithZone:(NSZone *)zone
{
CustomClass *copy = [[[self class] allocWithZone: zone] init];
return copy;
}
@end
現在,我想只是添加這些對象之一,一個簡單的字符串值,然後獲取字符串值退出登錄到控制檯:
CustomClass *newObject = [[CustomClass alloc] init];
NSString *valueString = @"Test string";
NSMutableDictionary *dict =
[[NSMutableDictionary alloc] initWithObjectsAndKeys:valueString, newObject, nil];
NSLog(@"Value in Dictionary: %@", [dict objectForKey: newObject]);
// Should output "Value in Dictionary: Test string"
不幸的是,日誌顯示一個(null)。我很確定我錯過了一些非常明顯的東西,並且覺得我需要另一雙眼睛。
返回方法'allKeys'是什麼? – Nekto