I created some json data and saved it in a file named quizdata.json in xcode. I then selected the project target and clicked on Editor/ Add Build Phase/ Add Copy File Build Phase, selected the Products Directory and dropped the quizdata.json file in the space provided. I did not indicate a subpath because I read it wasn't needed and I don't know it :(
I then added the four lines at the bottom of this main function to import the file and serialize it into an object. However, when I run the code it's showing null when the json data should be output
Imported Questions: (null)
Program ended with exit code: 0
Can you explain why it's null?
main int main(int argc, const char * argv[]) {
@autoreleasepool {
// Create the managed object context
NSManagedObjectContext *context = managedObjectContext();
// Custom code here...
// Save the managed object context
NSError *error = nil;
if (![context save:&error]) {
NSLog(@"Error while saving %@", ([error localizedDescription] != nil) ? [error localizedDescription] : @"Unknown Error");
exit(1);
}
NSError* err = nil;
NSString* dataPath = [[NSBundle mainBundle] pathForResource:@"quizdata" ofType:@"json"];
NSArray* Questions = [NSJSONSerialization JSONObjectWithData:[NSData dataWithContentsOfFile:dataPath]
options:kNilOptions
error:&err];
NSLog(@"Imported Questions: %@", Questions);
}
return 0;
}
Sample from quizdata.json
[{ "question" : "Do you like hairy fruit ?????????????????????????????", "answer1": "yes", "answer2": "no because my mouhth is like a large elastic band on tuesdays", "answer3": "maybe wonder never tried it but i should naturally", "answer4":"of course i do you beast of a man with a hairy nose", "correctAnswer": "yes", "unique": "1", "name": "fruitquiz", "quizId: 1"}
{ "question" : "Do you like fruit", "answer1": "yes", "answer2": "no", "answer3": "maybe", "answer4":"of course", "correctAnswer": "yes", "unique": "2", "name": "fruitquiz", "quizId: 1"}
...
if(err) NSLog("Error %@",[err description]);- Lukasz 'Severiaan' Grela