我的问题在哪里?我想用我的json填充我的coredata,但它只填充最后一个对象,我的意思是这个:
phone.name = [[[json valueForKey:@"boxesDetail"] objectAtIndex:1] valueForKey:@"name"];
phone.number = [NSNumber numberWithInt:[[[[json valueForKey:@"boxesDetail"] objectAtIndex:1] valueForKey:@"number"] intValue]];
而不是以前的。
这是我的代码:
- (void) add{
NSManagedObjectContext *context = [app managedObjectContext];
Phone *phone = [NSEntityDescription insertNewObjectForEntityForName:@"Phone" inManagedObjectContext:context];
if (nameText.text.length <= 0 || numberText.text.length <= 0)
{
NSLog(@" hey hey, t'as pas oublié kkchose ?");
}
else
{
phone.name = nameText.text;
phone.number = [NSNumber numberWithInt:[ numberText.text intValue]];
NSLog(@"ADD : %@", phone.name);
[[NSNotificationCenter defaultCenter] postNotificationName:@"Test" object:self];
[self dismissModalViewControllerAnimated:YES];
}
NSString *urlString = [NSString stringWithFormat:@"http://localhost:8888/json.txt"];
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:urlString]];
NSError *err;
NSMutableArray *json = (NSMutableArray* )[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&err];
for (int i = 0; i != 2; i++)
{
phone.name = [[[json valueForKey:@"boxesDetail"] objectAtIndex:i] valueForKey:@"name"];
phone.number = [NSNumber numberWithInt:[[[[json valueForKey:@"boxesDetail"] objectAtIndex:i] valueForKey:@"number"] intValue]];
}
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Phone" inManagedObjectContext:context];
[request setEntity:entity];
NSArray *array = [context executeFetchRequest:request error:&err];
for (Phone *pho in array)
{
NSLog(@"NAME %@", pho.name);
NSLog(@"PHONE %@", pho.number);
}
}
顺便说一句,如果你有一个想法让我不编写循环来填充核心数据,我会感谢你^^