2009-09-17 82 views
2

我需要一些关于KVC的帮助。KVC:如何测试现有密钥

有关操作上下文几句:

1)iPhone连接(客户端)到WebService获取对象,

2)我使用JSON来传输数据,

3)如果客户端有完全相同的对象映射,我可以遍历JSON中的NSDictionary以将数据存储在永久存储区(coreData)中。 要做到这一点,我用这个代码片段(假设全部数据的NSString):

NSDictionary *dict = ... dictionary from JSON 

NSArray *keyArray = [dict allKeys]; //gets all the properties keys form server 

for (NSString *s in keyArray){ 

[myCoreDataObject setValue:[dict objectForKey:s] forKey:s]; //store the property in the coreData object 

} 

现在我的问题....

4)如果服务器实现了新的版本,会发生什么具有1个新属性的对象 如果我将数据传输到客户端,并且客户端未处于保存版本级别(这意味着仍在使用“旧”对象映射),我会尝试为非客户端分配值现有的密钥...我将会收到以下消息:

实体“myOldObject”不是密钥va为密钥“myNewKey”符合lue编码

您能否建议我如何测试对象中是否存在该键,如果该键存在,则可以继续进行值更新以避免错误信息 ?

对不起,如果我在我的上下文解释有点困惑。

感谢

达里奥

回答

3

虽然我不能想办法,找出将一个对象的支持,你可以用什么键的事实,当你不存在的键的默认行为设定的值你的对象是throw an exception。您可以将setValue:forKey:方法调用放在@try/@catch块中以处理这些错误。

考虑下面的代码为对象:

@interface KVCClass : NSObject { 
    NSString *stuff; 
} 

@property (nonatomic, retain) NSString *stuff; 

@end 

@implementation KVCClass 

@synthesize stuff; 

- (void) dealloc 
{ 
    [stuff release], stuff = nil; 

    [super dealloc]; 
} 

@end 

这应该是KVC兼容的关键stuff,但没有别的。

如果从下面的程序访问该类:

int main (int argc, const char * argv[]) { 
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; 

    KVCClass *testClass = [[KVCClass alloc] init]; 

    [testClass setValue:@"this is the value" forKey:@"stuff"]; 

    NSLog(@"%@", testClass.stuff); 

    // Error handled nicely 
    @try { 
     [testClass setValue:@"this should fail but we will catch the exception" forKey:@"nonexistentKey"]; 
    } 
    @catch (NSException * e) { 
     NSLog(@"handle error here"); 
    } 

    // This will throw an exception 
    [testClass setValue:@"this will fail" forKey:@"nonexistentKey"]; 

    [testClass release]; 
    [pool drain]; 
    return 0; 
} 

您将得到类似于以下控制台输出:

2010-01-08 18:06:57.981 KVCTest[42960:903] this is the value 
2010-01-08 18:06:57.984 KVCTest[42960:903] handle error here 
2010-01-08 18:06:57.984 KVCTest[42960:903] *** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<KVCClass 0x10010c680> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key nonexistentKey.' 
*** Call stack at first throw: 
(
    0 CoreFoundation      0x00007fff851dc444 __exceptionPreprocess + 180 
    1 libobjc.A.dylib      0x00007fff866fa0f3 objc_exception_throw + 45 
    2 CoreFoundation      0x00007fff85233a19 -[NSException raise] + 9 
    3 Foundation       0x00007fff85659429 -[NSObject(NSKeyValueCoding) setValue:forKey:] + 434 
    4 KVCTest        0x0000000100001b78 main + 328 
    5 KVCTest        0x0000000100001a28 start + 52 
    6 ???         0x0000000000000001 0x0 + 1 
) 
terminate called after throwing an instance of 'NSException' 
Abort trap 

这表明第一次尝试访问关键nonexistentKey被该程序很好地捕获,第二个产生了一个类似于你的异常。