0
哪裏是我的probleme?我想填充我coredata與我的JSON,但其僅填充的最後一個對象,我的意思是這一個:核心數據,填充我Coredata與我的JSON
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);
}
}
順便說一句,如果你有一個想法,使我不能編碼一個循環來填充核心數據,我會感謝你^^