我在核心数据中有一些数据,我想将其转换为字符串,以便我可以将其发送回我的Web服务器。这是我到目前为止的代码:将数组从核心数据转换为JSON字符串的最佳方法?
NSError *error = nil;
NSFetchRequest *unfinishedTime = [[NSFetchRequest alloc] init];
NSEntityDescription *timeEntity = [NSEntityDescription entityForName:@"TimeEntries" inManagedObjectContext:context];
[unfinishedTime setEntity:timeEntity];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"timeStart != nil AND timeEnd != nil"];
[unfinishedTime setPredicate:predicate];
NSArray *timeArray = [context executeFetchRequest:unfinishedTime error:&error];
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:timeArray options:NSJSONWritingPrettyPrinted error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
它给我一个错误的NSData行。从我所知道的情况来看,timeArray中有5个对象。我敢肯定,这是一个非常简单的错误,我可能会以这种错误的方式来解决这个问题。
我为所有核心数据模型写了toDictionary方法。当我需要将它们转换为JSON或记录它时,它变得很容易。 – JeffRegan