【发布时间】:2015-10-18 16:45:58
【问题描述】:
我正在尝试将 JSON 数组转换为对象以在表格中显示。我能够捕获 JSON。但是,当我尝试变成对象时,出现如下所示的错误。在对象类中肯定有一个名为“name”的属性。
- (void)fetchedData:(NSData *)responseData {
NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseData
options:kNilOptions
error:&error];
NSMutableArray* latestItems = nil;
latestItems = [[NSMutableArray alloc] init];
latestItems = [json objectForKey:@"items"];
[self.tableView reloadData];
for (int i = 0; i < latestItems.count; i++)
{
NSDictionary *itemElement = latestItems[i];
// Create a new l object and set its props to todoElement properties
IDItemFromServer *newItem = [[IDItemFromServer alloc] init];
//ERROR NEXT LINE THROWS FOLLOWING ERROR
//'NSUnknownKeyException', reason: '[<IDItemFromServer 0x14e88010> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key name.'
[newItem setValue:@"hi" forKey:@"name"];
[newItem setValue:itemElement[@"address"] forKey:@"address"];
// Add this new item to the array
[latestItems addObject:newItem];
}
如果有任何关于如何修复错误的建议,我们将不胜感激。
编辑:
//Object.h file
#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>
@interface IDItemFromServer : NSObject
@property (nonatomic, retain) NSNumber * iid;
@property (nonatomic, retain) NSString * name;
@property (nonatomic, retain) NSString * address;
@end
【问题讨论】:
-
该错误表明没有名为
name的属性。使用有关IDItemFromServer类接口的详细信息更新您的问题。 -
如果您有一个不错的公共财产,为什么不直接使用
newItem.name = @"hi";而不是使用setValue:forKey:? -
我之前尝试过这个,它给了我 //[IDItemFromServer setName:]: unrecognized selector sent to instance 0x16d7dfd0 错误,但是,我会再试一次。
-
是的,它正在抛出 IDItemFromServer setName:]: unrecognized selector sent to instance 0x15599ed0' that way
-
当属性在运行时而不是编译时合成时,您只需要
@dynamic。