KVC:如何测试现有密钥

发布于 2024-08-04 21:51:34 字数 812 浏览 9 评论 0原文

我需要一些关于 KVC 的帮助。

关于操作上下文的几句话:

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

2)我使用 JSON 传输数据,

3)如果客户端具有完全相同的对象映射,我可以迭代NSDictionary 来自 JSON 将数据存储在永久存储(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”与键“myNewKey”的键值编码不兼容

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

抱歉,如果我的上下文解释有点令人困惑。

谢谢

达里奥

I need a little help about KVC.

Few words about the operating context:

1) The iPhone connects (client) to a webService to get an object,

2) I'm using JSON to transfer data,

3) If the client has exactly the same object mapping I can iterate through the NSDictionary from JSON to store the data in the permanent store (coreData).
To do that I'm using this code fragment (assume that are all data are 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 

}

Now my problem ....

4) What happen if the server implementing a new version of the object with 1 new property
If I transfer the data to the client and the client is not at the save version level (it means is still using the "old" object mapping) I'll try to assign a value for a non existing key... and I will have the message:

the entity "myOldObject" is not key value coding-compliant for the key "myNewKey"

Could you suggest me how to test for the existence of the key in the object so, if the key exists, I'll can proceed to the value update avoiding the error message ?

Sorry if I have been a little confusing in my context explanation.

Thanks

Dario

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

失退 2024-08-11 21:51:34

虽然我想不出一种方法来找出对象支持哪些键,但您可以利用以下事实:当您为不存在的键设置值时,对象的默认行为是 抛出异常。您可以将 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 标准,但没有其他内容。

如果您从以下程序访问此类:

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 的尝试,第二次尝试生成与您类似的例外。

While I can't think of a way to find out what keys will an object support you could use the fact that when you set the value for a nonexistent key the default behaviour of your object is to throw an exception. You could enclose the setValue:forKey: method invocation in a @try / @catch block to handle these errors.

Consider the following code for an object:

@interface KVCClass : NSObject {
    NSString *stuff;
}

@property (nonatomic, retain) NSString *stuff;

@end

@implementation KVCClass

@synthesize stuff;

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

    [super dealloc];
}

@end

This should be KVC-compliant for the key stuff but nothing else.

If you access this class from the following program:

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;
}

You will get a console output similar to the following:

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

This shows that the first attempt to access the key nonexistentKey was nicely caught by the program, the second one generated an exception similar to yours.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文