JSON to Persistent Data Store (CoreData, etc.)

前端 未结 2 1665
臣服心动
臣服心动 2021-01-30 05:48

All of the data on my application is pulled through an API via JSON. The nature of a good percentage of this data is that it doesn\'t change very often. So to go and make JSON r

2条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-30 06:16

    For some conceptual reading, you may want to read documentation about Efficiently Importing Data, especially "Find-or-create". See a previous similar question.

    Getting JSON and saving it as Core Data locally is highly reasonable. How I do it is in two stages:

    1. convert JSON to native Cocoa data types (NSDictionary and NSArray)
    2. convert NS* into Core Data object

    Two good frameworks for converting between JSON and NS* are json-framework and TouchJSON. The below example is based on json-framework.

    Let's say you get an array of some objects from JSON. You'd then do:

    NSArray *objects = [jsonStringYouGotFromServer JSONValue];
    for (NSDictionary *_object in objects) {
        CDObjectType *cdObject = [self cdObjectFromDictionary:_object];
        // cdObject is now a full-featured Core Data object
    }
    

    the cdObjectFromDictionary might be something like this:

    - (CDObjectType *) cdObjectFromDictionary:(NSDictionary *)dict {
    
        CDObjectType *object = [NSEntityDescription
                  insertNewObjectForEntityForName:@"Object"
                  inManagedObjectContext:moc];
    
        NSDictionary *attributes = [[NSEntityDescription
            entityForName:@"Object"
            inManagedObjectContext:moc] attributesByName];
    
        for (NSString *attr in attributes) {            
            [object setValue:[dict valueForKey:attr] forKey:attr];                            
        }
    
        return object;
    }
    

    The above assumes that the attribute names in your JSON and Core Data model are the same and that the data types match (i.e JSON numbers are Core Data NSNumbers etc). The above code works nicely even if the model changes.

    The above code does not consider how to test if the object already exists locally, but you can imagine how to add that. You must have an object ID of some form in your model, and you can see if the object exists locally before adding it, or whether existing object needs to be updated.

提交回复
热议问题