Using valueForKeyPath on NSDictionary if a key starts the @ symbol?

谁说我不能喝 提交于 2019-11-29 01:21:31
pxl

you shouldn't be using @ signs with your key names if you want to use key value coding.

apple's guidelines for key names are as follows:

Keys must use ASCII encoding, begin with a lowercase letter, and may not contain whitespace.

You'll have to find a workaround to reformat the key string whereever you're getting your keys from to be KVC compliant.

Just to update this old question a little...

The reason that these:

[dict valueForKeyPath:@"key1.@specialKey.key3"]
[dict valueForKeyPath:@"key1.@@specialKey.key3"]

...fail is that any "@" symbols in a key path are interpreted as being collection's operators as with:

[dict valueForKeyPath:@"key1.@sum.key3"] // returns the sum of all 'key3' values
[dict valueForKeyPath:@"key1.@avg.key3"] // returns the average of all 'key3' values

The nested key calls:

[[[dict objectForKey:@"key1"] objectForKey:@"@specialKey"] objectForKey:@"key3"]

... work because a single key is not processed as a key path.

If you have no control over the naming, how about adding a category with a properly named key that simply returns/sets the weird key?

I see that there are 2 ways

Swizzle

You can swizzle the valueForKeyPath on NSDictionary to remove the @ symbol, remember to account for @sum, @average, ...

Override if you're using Mantle

Override + (id)modelOfClass:(Class)modelClass fromJSONDictionary:(NSDictionary *)JSONDictionary on MTLJSONAdapter, traverse all the keys and remove the @ symbol

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!