从JSON

时间:2015-10-18 15:40:57

标签: ios objective-c json core-data

我需要下载一些JSON以便在表格中显示,并尝试关注this tutorial。我可以把JSON变成一个数组。但是,当我尝试将它放入一个对象时,我收到两个错误,如下所示。

- (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
//ERROR 1  NEXT LINE THROWS FOLLOWING ERROR:
// CoreData: error: Failed to call designated initializer on NSManagedObject class 'IDItemFromServer' 
        IDItemFromServer *newItem = [[IDItemFromServer alloc] init];
//ERROR 2  NEXT LINE THROWS FOLLOWING ERROR
//[IDItemFromServer setName:]: unrecognized selector sent to instance 0x16d7dfd0
        newItem.name = itemElement[@"name"];
        newItem.address = itemElement[@"address"];

        // Add this new item  to the array
        [latestItems addObject:newItem];
    }

非常感谢有关如何解决此问题的任何建议。

1 个答案:

答案 0 :(得分:1)

错误1:

必须使用指定的初始化程序

初始化NSManagedObject的实例
- (__kindof NSManagedObject * _Nonnull)initWithEntity:(NSEntityDescription * _Nonnull)entity insertIntoManagedObjectContext:(NSManagedObjectContext * _Nullable)context

或者使用类方法

+ (__kindofNSManagedObject *)insertNewObjectForEntityForName:(NSString *)entityName inManagedObjectContext:(NSManagedObjectContext *)context
NSEntityDescription

错误2:

如果IDItemFromServer不是NSManagedObject的自定义子类,则必须使用

访问属性

吸气剂:

- (id _Nullable)valueForKey:(NSString * _Nonnull)key

设定器:

- (void)setValue:(id _Nullable)value forKey:(NSString * _Nonnull)key