Was advised to post this question here after posting to Stack Overflow. I'm pre-populating a UITableView app with data using a local JSON file. The JSON itself is very simple:
[
{"Name":"Tennis Ball Launchers",
"Type":"Forces"},
{"Name":"Magnetic Hot Plates",
"Type":"Magnetism"},
{"Name":"Giant Lever",
"Type":"Forces"},
{"Name":"Music Wall",
"Type":"Sound"},
{"Name":"Water Bearing",
"Type":"Forces"},
{"Name":"Chaos Pendulums",
"Type":"Chaos"}
]
The JSON objects will have more properties further down the line, this is just for starters (there will be around 200 entries by the end, with more properties). I don't imagine the structure getting any more complex, however. The user will not be adding or deleting entries in the app - the JSON is read only. I want to map these JSON objects into an array of custom NSObjects. Here is the code I am currently using in the initialisation of my data model:
// JSON reading into array
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"json"];
NSError *error;
NSString *fileContents = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:&error];
if(error) {
NSLog(@"Error reading file: %@", error.localizedDescription);
}
// Get JSON objects into initial array
NSArray *rawExhibits = (NSArray *)[NSJSONSerialization JSONObjectWithData:[fileContents dataUsingEncoding:NSUTF8StringEncoding] options:0 error:NULL];
NSMutableArray *myItems = [[NSMutableArray alloc] init];
for (NSDictionary *object in rawExhibits) {
NSString *objectName = object[@"Name"];
NSString *objectType = object[@"Type"];
// Create new exhibit object with data procured from JSON object
W5BExhibit *exhibit = [[W5BExhibit alloc] initWithExhibitName:objectName exhibitType:objectType];
[myItems addObject:exhibit];
}
self.allExhibits = [[NSArray alloc] initWithArray:myItems];
The table view can then refer to the allExhibits variable which is a property of a singleton. I'm very new at this so I'm canvassing for opinions.
I was also advised to consider using keyed archiving to persist the data instead of parsing the JSON each time the app is opened up from new.