2009-09-17 86 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被該程序很好地捕獲,第二個產生了一個類似於你的異常。