0

我的问题在哪里?我想用我的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);
    }

}

顺便说一句,如果你有一个想法让我不编写循环来填充核心数据,我会感谢你^^

4

1 回答 1

0

您仅在此行中创建一个托管对象:

NSManagedObjectContext *context = [app managedObjectContext];

然后在这些行中设置名称和编号字段 3 次:

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]];
}
于 2012-04-30T16:03:49.613 回答