有时ObjectForKey返回nil

时间:2019-04-27 17:29:04

标签: objective-c macos nsmutabledictionary

我试图将一个对象设置为以键为对象的字典。测试用例工作正常,但是在实际代码中,我无法获取键的值。 NSMutableDictionary中包含键值,但是在调试时返回nil

@implementation JSHashMap {
    NSMutableDictionary *dict;
}

- (instancetype)initWithArray:(NSMutableArray *)array {
    self = [super init];
    if (self) {
        dict = [self fromArray:array];
    }
    return self;
}

- (NSMutableDictionary *)fromArray:(NSMutableArray *)array {
    NSMutableDictionary* _dict = [NSMutableDictionary new];
    NSUInteger i = 0, len = [array count];
    if (len % 2 != 0) {
        error(@"JSError: Odd number of elements in the array.");
        return _dict;
    }
    for (i = 0; i < len; i = i + 2) {
        [_dict setObject:array[i + 1] forKey:array[i]];
        assert([_dict objectForKey:array[i]] != nil);
    }
    debug(@"%@", _dict);
    return _dict;
}

- (JSData *)objectForKey:(id)key {
    return [dict objectForKey:key];
}

我正在使用initWithArray方法创建哈希图。

(lldb) po [dict objectForKey:key]
 nil

传入的key和字典中的键具有相同的内存地址0x100ea2fa0

screenshot - debug variables

尽管测试用例工作正常。但是当运行实际程序时,它会失败。

NSMutableDictionary *dict = [NSMutableDictionary new];
JSNumber *val = [[JSNumber alloc] initWithInt:1];
JSNumber *key = [[JSNumber alloc] initWithInt:2];
[dict setObject:val forKey:key];
JSData * ret = [dict objectForKey:key];
XCTAssertNotNil(ret);
XCTAssertEqualObjects([ret dataType], @"JSNumber");
JSHashMap *hm = [[JSHashMap alloc] initWithArray:[@[key, val] mutableCopy]];
JSData * ret1 = [hm objectForKey:key];
XCTAssertNotNil(ret1);
XCTAssertEqualObjects([ret1 dataType], @"JSNumber");
JSHashMap *dict = (JSHashMap *)ast;
NSArray *keys = [dict allKeys];
NSUInteger i = 0;
NSUInteger len = [keys count];
for (i = 0; i < len; i++) {
    id key = keys[i];
    JSData *val = (JSData *)[dict objectForKey:key];
    // Issue -> val is getting nil 
}

如何解决此问题,为什么会有这种随机行为?


找到失败的测试用例。

NSArray *keys = [hm allKeys];
XCTAssertTrue([keys count] == 1);
JSData *ret = [hm objectForKey:keys[0]];
XCTAssertNotNil(ret);

如果我使用从调用allKeys方法返回的键,它将返回nil。

1 个答案:

答案 0 :(得分:3)

您尚未显示有关JSNumber是什么的任何信息,但我敢打赌它无法正确实现isEqualhash。因此,您不能成功地将其用作NSDictionary中的密钥。