2012-04-30 42 views
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); 
    } 

} 

順便說一句,如果你有一個想法,使我不能編碼一個循環來填充核心數據,我會感謝你^^

回答

0

你只創建一個在這條線的管理對象:

NSManagedObjectContext *context = [app managedObjectContext]; 

然後設置的名稱和號碼字段在這些行三次:

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]]; 
} 

我猜你要創建和填充三個對象,而不只是一個。將循環內的管理對象的創建。

for (int i = 0; i != 2; i++) 
{ 
    Phone *phone = [NSEntityDescription insertNewObjectForEntityForName:@"Phone" inManagedObjectContext:context]; 
    phone.name = [[[json valueForKey:@"boxesDetail"] objectAtIndex:i] valueForKey:@"name"]; 
    phone.number = [NSNumber numberWithInt:[[[[json valueForKey:@"boxesDetail"] objectAtIndex:i] valueForKey:@"number"] intValue]]; 
}