setValue:forUndefinedKey此类不符合键值编码

Blu*_*eni 5 objective-c ios

我有一个看起来像这样的nsmutablearray:

(
        {
        caption = "";
        urlRep = "assets-library://asset/asset.JPG?id=6FC0C2DC-69BB-4FAD-9709-63E03182BEE1&ext=JPG";
    },
        {
        caption = "";
        urlRep = "assets-library://asset/asset.JPG?id=324E4377-0BCD-431C-8A57-535BC0FC44EB&ext=JPG";
    }
)
Run Code Online (Sandbox Code Playgroud)

我试图像这样设置标题的值:

[[[self.form valueForKey:@"photos"] objectAtIndex:indexPath.row] setValue:@"hi" forKey:@"caption"];
Run Code Online (Sandbox Code Playgroud)

([self.form valueForKey:@"photos"]是数组)

但我得到:

*** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<__NSDictionaryI 0xa68ec40> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key caption.'
Run Code Online (Sandbox Code Playgroud)

编辑:

如果我使用setObject forKey我得到:

-[__NSDictionaryI setObject:forKey:]: unrecognized selector sent to instance 0xa6a88f0
 *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSDictionaryI setObject:forKey:]: unrecognized selector sent to instance 0xa6a88f0'
Run Code Online (Sandbox Code Playgroud)

我该如何解决?

修正此代码的正确代码:

NSMutableDictionary *m = [[[self.form valueForKey:@"photos"] objectAtIndex:indexPath.row ] mutableCopy];
NSMutableArray *array = [self.form valueForKey:@"photos"];
[m setObject:textField.text forKey:@"caption"];
[array replaceObjectAtIndex:indexPath.row withObject:m];
Run Code Online (Sandbox Code Playgroud)

tro*_*foe 22

获得异常的原因是因为您有一个NSDictionary对象数组,它们不响应setObject:forKey:(或setValue:forKey:).

您可能希望在NSMutableDictionary收到对象后立即将它们全部转换为对象.

  • @BluGeni使用`mutableCopy`制作副本. (4认同)