Es wurde versucht, die JSON-Datei in Objective-C zu lesen
Ich versuche, eine JSON-Datei in meiner Objective-C-Anwendung einzulesen, erhalte jedoch leider eine RuntimeException. Der genaue Fehler ist:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'data parameter is nil'
Meine json-Datei heißt "Transactions.json"
[{ "transaction": "300001", "date": "1/1/11", "type": "ABC", "status": "State1" },
{ "transaction": "300002", "date": "2/2/12", "type": "XYZ", "status": "State2" },
{ "transaction": "300003", "date": "3/3/13", "type": "ABC", "status": "State3" },
{ "transaction": "300004", "date": "2/2/12", "type": "XYZ", "status": "State2" },
{ "transaction": "300005", "date": "3/3/13", "type": "ABC", "status": "State3" },
{ "transaction": "300006", "date": "2/2/12", "type": "XYZ", "status": "State2" },
{ "transaction": "300007", "date": "3/3/13", "type": "ABC", "status": "State3" },
{ "transaction": "300008", "date": "2/2/12", "type": "XYZ", "status": "State2" },
{ "transaction": "300009", "date": "3/3/13", "type": "ABC", "status": "State3" },
{ "transaction": "300010", "date": "4/4/14", "type": "XYZ", "status": "State4" } ]
Meine Methode, die die Datei einliest, sieht folgendermaßen aus:
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:@"Transactions" ofType:@"json"];
NSLog(@"Hello: %@", dataPath);
NSArray *transaction = [NSJSONSerialization JSONObjectWithData:[NSData dataWithContentsOfFile:dataPath] options:kNilOptions error:&err];
NSLog(@"Transaction list: %@", transaction);
}
return 0;
}
Ich verstehe nicht, warum das NSData-Objekt beim Lesen der JSON-Datei als null angezeigt wird. Kann jemand sehen, was ich falsch mache? Nur zur Veranschaulichung, ich habe versucht, meine JSON-Datei auf überflüssige Leerzeichen zu überprüfen und die JSON-Datei an verschiedenen Stellen in meinem Anwendungsordner abzulegen, und es hat nichts funktioniert.
Vielen Dank im Voraus an alle, die antworten.