0

我在使用 NSDictionnary 时遇到了一个奇怪的问题......

我正在尝试为存在的键检索对象,该键是具有方法 objectForKey 的字典,但它返回 nil。

当我打印出整个字典时,我可以清楚地看到我正在寻找的键和值。

这是代码:

- (MObject *)GetWithMProperty:(MProperty *)prop {
    NSLog(@"We search an object for a property named %@", prop.Name);
    NSArray *keyArray =  [_dict allKeys];
    int count = [keyArray count];
    for (int i=0; i < count; i++) {
        MObject *tmp = [_dict objectForKey:[ keyArray objectAtIndex:i]];
        NSLog(@"Key = %@ | Object = %d", ((MProperty*)[keyArray objectAtIndex:i]).Name, tmp.GetTypeId);
        if (prop == [keyArray objectAtIndex:i])
            NSLog(@"Wouhou !");
        else
            NSLog(@"Too bad :(");
    }
    return [_dict objectForKey:prop];
}

和堆栈跟踪:

2012-10-29 11:24:07.730 IOS6[1451:11303] We search an object for a property named Value
2012-10-29 11:24:07.730 IOS6[1451:11303] Key = Name | Object = 4
2012-10-29 11:24:07.731 IOS6[1451:11303] Too bad :(
2012-10-29 11:24:07.731 IOS6[1451:11303] Key = Value | Object = 0
2012-10-29 11:24:07.732 IOS6[1451:11303] Too bad :(

这有点复杂,我正在使用 J2ObjC 编译一个功能齐全的引擎,因此我无法修改 MProperty 和 MObject 类(由引擎使用)。

MProperty 不符合 NSCopying 协议,所以我创建了一个名为 IPhoneMProperty 的类,它继承自 MProperty 并符合协议。

这是这个类:

@implementation IPhoneMProperty

- (id)initWithMProperty:(MProperty *)prop {
    self = [super initWithInt:prop.OwnerTypeId withNSString:prop.Name withInt:prop.TypeId withMBasicValue:prop.DefaultValue withInt:prop.Flags];
    return self;
}

- (id)copyWithZone:(NSZone *)zone {
    IPhoneMProperty *prop = [[IPhoneMProperty alloc] initWithMProperty:self];
    return prop;
}

@end

我用来向字典添加对象和键的方法:

- (void)SetWithMProperty:(MProperty *)prop withMObject:(MObject *)obj {
    IPhoneMProperty *tempKey = [[IPhoneMProperty alloc] initWithMProperty:prop];
    [_dict setObject:obj forKey:tempKey];
}

我希望它足够清楚,实际上这是我目前找到的唯一解决方案,但它不起作用:(

任何人都可以帮助我吗?

谢谢 !

4

3 回答 3

1

问题存在于线路

    if (prop == [keyArray objectAtIndex:i])

相反,在你的类中实现isEquals:方法。MProperty

-(BOOL)isEquals:(MProperty*)inProp {
  if( [inProp.name isEqualToString:self.name] )return YES;

  return NO;
}

而且,在这里,而不是线

    if (prop == [keyArray objectAtIndex:i])

使用以下行,

    if ([prop isEquals [keyArray objectAtIndex:i]])
于 2012-10-29T10:46:04.840 回答
0

你在使用前分配了你的 _dict 对象吗?

如下修改您的代码并检查。

- (void)SetWithMProperty:(MProperty *)prop withMObject:(MObject *)obj {
    IPhoneMProperty *tempKey = [[IPhoneMProperty alloc] initWithMProperty:prop];
    if(!_dict) 
        _dict = [[NSMutableDictionay alloc]init];
    [_dict setObject:obj forKey:tempKey];
}

希望对你有效。

于 2012-10-29T10:46:20.997 回答
0

您可以尝试更改 if 条件以比较字符串之间的值吗?像这样 :

if ([prop.Name isEqualToString:((MProperty*)[keyArray objectAtIndex:i]).Name])
            NSLog(@"Wouhou !");
        else
            NSLog(@"Too bad :(");
    }
于 2012-10-29T10:51:04.657 回答