Project requirements: After getting the JSON from the network, the JSON is automatically dumped into the coredata.
Following the previous log, the main content of this article is to save the JSON to CoreData.
To tell the truth, is nothing but KVC assignment, the idea is clear, but I am thinking of a problem, there is no way to do GM? So the question comes ~ Digging machine technology which strong!
Ok no nonsense, although KVC temporarily meet my project needs, the general approach I am still looking for, limited capacity, but I will work hard.
By the way, share a description of the network request data deposited to CoreData
Process remote service data into Core data
============ ============ ============ ============ ======
Well, we have the data persisting to disk in a property List format. But "What are you really want to" to "to" process it into Core Data. This is where you'll be doing some heavy lifting and getting into the nitty gritty details. The the part where the real magic happens!
To start off you'll first need a-retrieve the files from disk. Add-jsondictionaryforclasswithname:in SDSYNCENGINE.M:
-(Nsdictionary *) Jsondictionaryforclasswithname: (NSString *) className {Nsurl *fileurl = [Nsurl Urlwithstring:classnam e relativetourl:[self Jsondatarecordsdirectory]]; return [Nsdictionary Dictionarywithcontentsofurl:fileurl];}
One caveat to the Nsdictionary That-jsondictionaryforclasswithname:returns is and the information you be interested in Is would be a nsarray with the key "results". Make things easier for processing purposes, add another method to access the data in the Nsarray and spice it up a l Ittle to allow for sorting of the records by a specified key.
Add this beneath-jsondictionaryforclasswithname:in SDSYNCENGINE.M:
- (nsarray *) Jsondatarecordsforclass: ( nsstring *) Classname sortedbykey: (nsstring *) key { nsdictionary *JSONDictionary = [self JSONDictionaryForClassWithName:className]; nsarray *records = [jsondictionary objectforkey:@ "Results"]; return [records sortedarrayusingdescriptors:[nsarray arraywithobject: [NSSortDescriptor sortDescriptorWithKey:key Ascending:yes]];}
This method calls the previous method for you implemented, and returns a nsarray of all the records in the response, sorted b Y the specified key.
You won ' t really need the JSON responses that were saved to disk much past this point, so add another method to delete the m when your ' re finished with them. Add the following method Above-jsondictionaryforclasswithname:
- (void) Deletejsondatarecordsforclasswithname: ( nsstring *) Classname { nsurl *url = [nsurl urlwithstring: Classname relativetourl:[self jsondatarecordsdirectory]]; nserror *error = nil; bool deleted = [[nsfilemanager defaultmanager] removeItemAtURL:url error:&error]; if (!deleted) { nslog (@ "unable to delete json records at %@, reason: %@ ", url, error); }}
In the order to translate records from the JSON to nsmanagedobjects, you'll need a few methods. First, you'll need to translate the JSON values to objective-c properties; The method you use would vary based on the remote service is working with. In this case, you are using the Parse which has a few "special" data types. The data you'll be concerned with here is Files and Dates. Files is returned as URLs to the file's location, and Dates is returned in the following format:
{"__type": "Date", "ISO": "2011-08-21t18:02:52.249z"}
Since the date is in the format of a string, you'll want some methods to convert from a Parse formatted date string to a n NSDate and back to an nsstring. NSDateFormatter can help with this, but they is very expensive to allocate-so first add a new NSDateFormatter property That's you can re-use.
Add the Dateformatter property in your private category:
@interface Sdsyncengine () @property (nonatomic, strong) Nsmutablearray *registeredclassestosync; @property (Nonatomic, Strong) NSDateFormatter *dateformatter; @end
and add these three methods above the #pragma mark-file Management.
- (void) initializedateformatter { if (!self.dateformatter) { self.dateFormatter = [[NSDateFormatter alloc] init]; [self.dateformatter setdateformat:@ "Yyyy-MM-dd T ' HH : Mm:ss ' Z ' "]; [self.dateformatter settimezone:[nstimezone timezonewithname:@ "GMT"]]; }}- (nsdate *) Dateusingstringfromapi: ( nsstring *) datestring { [self initializedateformatter]; // NSDateFormatter does not like ISO 8601 so strip the milliseconds and timezone datestring = [datestring Substringwithrange:nsmakerange (0, [datestring length]-5)]; return [self.datefoRmatter datefromstring:datestring];} - (nsstring *) Datestringforapiusingdate: (nsdate *) date { [self initializedateformatter]; nsstring *datestring = [ self.dateformatter stringfromdate:date]; // remove z datestring = [datestring substringwithrange:nsmakerange (0, [dateString length]- 1)]; // add milliseconds and put z back on datestring = [datestring stringbyappendingformat:@ ". 000Z"]; return datestring;}
The first method-initializedateformatter would initialize your Dateformatter property. The second method-dateusingstringfromapi:receives an nsstring and returns an NSDate object. The third method-datestringforapiusingdate:receives an nsdate and returns an NSString.
Take a little closer look, there, detective-the second and third methods do something a little strange. Parse uses timestamps in the ISO 8601 format which does not translate to nsdate objects very well, so we need to do some St Ripping and appending of the milliseconds and Z flag (used to denote the timezone). (Oh Standards...there is so many wonderful ones to choose from!) :]
Next Add this method below Mostrecentupdatedatdateforentitywithname:
- (void) SetValue: (ID) Value forkey: (nsstring *) Key formanagedobject: (nsmanagedobject * ) managedobject { if ([key isequaltostring:@ "CreatedAt"] | | [key isequaltostring:@ "Updatedat"]) { nsdate *date = [self dateUsingStringFromAPI:value]; [managedObject setValue:date forKey:key]; } else if ([ Value iskindofclass:[nsdictionary class]]) { if ([value objectforkey:@ "__type"]) { nsstring *datatype = [value objectforkey:@ "__type"]; if ([datatype isequaltostring:@ "Date"]) { NSString *dateString = [value objectforkey:@ "ISO"]; NSDate *date = [self dateUsingStringFromAPI:dateString]; [managedobject setvalue: Date forkey:key]; } else if ([datatype isequaltostring:@ "File"]) { nsstring *urlstring = [value objectforkey: @ "url"]; nsurl *url = [NSURL URLWithString:urlString]; NSURLRequest *request = [NSURLRequest requestWithURL:url]; nsurlresponse * response = nil; NSError *error = nil; NSData *dataResponse = [NSURLConnection sendsynchronousrequest:request returningresponse:&response error:&error]; [managedobject setvalue: dataresponse forkey:key]; } else { NSLog (@ "Unknown data type reCeived "); [ managedobject setvalue:nil forkey:key]; } } } else { [managedObject setValue:value forKey:key]; }}
This method accepts a value, key, and ManagedObject. If The key is equal to CreatedDate or Updatedat, you'll be a converting them to nsdates. If The key is a nsdictionary you'll check the __type key to determine the data type, Parse returned. If It is a Date, you'll convert the value from an nsstring to an nsdate. If It is a File, you'll do a little more work since you be interested in getting the image itself!
To get the image, send off a request to download the image file. It's important to note that downloading the image data can take a considerable amount of time, so this can be work effi ciently with smaller data sets. Another solution would was to fetch the image data when the record was accessed (lazy loading), but it would was only availab Le if the user has a Internet connection at the time of the lazy loading.
If The data type is anything other than a File or Date there is the no-it-know-what-If-set the value to nil. In any other case you'll simply pass the value and key through untouched and set them on the ManagedObject.
Something:
Patient see here, actually I just want to prove a little, sure enough or kvc!
IOS Network request JSON automatically dump to CoreData (ii)