I am a newbie and I would like to store and retrieve data from a Core Data database.
I get all the data from a php file, which communicates with a SQL database. This php file returns a JSON object, which in turn is parsed by my app and then written into Core Data by doing the following:
AppDelegate.m
-(void)writeDataIntoCoreData
{
NSManagedObjectContext *context = [self managedObjectContext];
NSManagedObject *articles = [NSEntityDescription
insertNewObjectForEntityForName:@"Articles"
inManagedObjectContext:context];
for(int i= 0; i<[json count];i++){
NSDictionary *info = [json objectAtIndex:i];
NSNumberFormatter * f = [[NSNumberFormatter alloc] init];
[f setNumberStyle:NSNumberFormatterDecimalStyle];
NSNumber * myNumber = [f numberFromString:[info objectForKey:@"userID"]];
[articles setValue:myNumber forKey:@"articleID"];
[articles setValue:[info objectForKey:@"username"] forKey:@"author"];
[articles setValue:[info objectForKey:@"user_pic"] forKey:@"text"];
NSLog(@"Name = %@",[info objectForKey:@"username"]);
NSLog(@"Text = %@",[info objectForKey:@"user_pic"]);
}
NSError *error;
if (![context save:&error]) {
NSLog(@"Whoops, couldn't save: %@", [error localizedDescription]);
}
}
MainViewController.m
Here I try to retrieve all the data in the Core Data database by iterating through the fetchedObjects.
-(IBAction)showCD:(id)sender
{
NSManagedObjectContext *context = [self managedObjectContext];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription
entityForName:@"Articles" inManagedObjectContext:context];
[fetchRequest setEntity:entity];
NSError *error;
NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];
for (NSManagedObject *info in fetchedObjects) {
NSLog(@"id: %@", [info valueForKey:@"articleID"]);
NSLog(@"Name: %@", [info valueForKey:@"author"]);
NSLog(@"Text: %@", [info valueForKey:@"text"]);
}
}
The NSLog, however, only displays one object, namely the first one that was written into the database. What is wrong ?
move your
into your for loop,