0

我想将数据保存在核心数据中。

但保存的数据是唯一的最后数据。

我认为,重要的问题是唯一的!只要!保存最后一个数据。

其实我英文不太好...

请我想让你明白我的问题..

这是我的代码。

正如我解释这段代码。这个项目有一个样本。csv,所以我将该文件分开。并且分离的数据由“setvalue”保存。

这是什么问题??

 NSString *path = [[NSBundle mainBundle] pathForResource:@"Sample" ofType:@"csv"];
    NSString *strText = [NSString stringWithContentsOfFile:path encoding:NSEUCKREncoding error:nil];

    NSArray * array = [strText componentsSeparatedByString:@"\n"];

    NSString *tempText;
    int i = 0;
    NSArray * temparray;

    AppDelegate *appDelegate = [[UIApplication sharedApplication]delegate];
    NSManagedObjectContext *newContext = [appDelegate  managedObjectContext];
    NSManagedObject *newContact;
    newContact  = [NSEntityDescription insertNewObjectForEntityForName:@"Contacts" inManagedObjectContext:newContext];


    NSError *error;
    for(i = 1;i<[array count]-1;i++){
        tempText = [[array objectAtIndex:i]description];

        temparray = [tempText componentsSeparatedByString:@"##"];

        [newContact setValue:[temparray objectAtIndex:0] forKey:@"name"]; 
        [newContact setValue:[temparray objectAtIndex:1] forKey:@"phone"]; 
        [newContact setValue:[temparray objectAtIndex:2] forKey:@"sex"]; 

        [newContext save:&error];
    }
4

3 回答 3

1

我想,你应该把这个:

NSManagedObject *newContact;
newContact  = [NSEntityDescription insertNewObjectForEntityForName:@"Contacts" inManagedObjectContext:newContext];

进入 for 循环的第一行

于 2012-03-26T11:45:45.100 回答
1

您正在循环之外创建新实体,因此您只创建一个新实体。将此位移动到 for 循环的顶部:

newContact  = [NSEntityDescription insertNewObjectForEntityForName:@"Contacts" inManagedObjectContext:newContext];

喜欢:

for(i = 1;i<[array count]-1;i++){
    newContact  = [NSEntityDescription insertNewObjectForEntityForName:@"Contacts" inManagedObjectContext:newContext];
    tempText = [[array objectAtIndex:i]description];

    temparray = [tempText componentsSeparatedByString:@"##"];

    [newContact setValue:[temparray objectAtIndex:0] forKey:@"name"]; 
    [newContact setValue:[temparray objectAtIndex:1] forKey:@"phone"]; 
    [newContact setValue:[temparray objectAtIndex:2] forKey:@"sex"]; 

    [newContext save:&error];
}
于 2012-03-26T11:47:17.910 回答
0

您必须为每个临时数组插入一个新联系人。因此,您需要将 newContact = [NSEntityDescription insertNewObjectForEntityForName:@"Contacts" inManagedObjectContext:newContext];in 移至 for。

于 2012-03-26T11:46:28.647 回答