2012-03-26 3 views
0

코어 데이터에 데이터를 저장하고 싶습니다."Core Data"(iPhone)에 대해 잘 작업하고 싶습니다.

그러나 저장된 데이터 만 마지막 데이터입니다.

중요한 문제는 유일한 것 같습니다. 만! 마지막 하나의 데이터를 저장했습니다.

는 사실은 내가

이 내 코드입니다 .. 당신이 내 질문을 이해에 매우 잘 ...

내가 원하는하십시오 영어를 모른다.

나는이 코드를 설명한다. 이 프로젝트에는 샘플이 있습니다. 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]; 
    } 
+0

당신은 의도적 배열의 첫 번째 객체를 건너 뛰는? 인덱스 1로 루프를 시작하지만 배열의 첫 번째 오브젝트의 인덱스는 0입니다. –

+0

예, 의도적으로 .. 해결했습니다. :-) –

+0

좋습니다. 당신이 csv를 파싱한다는 것을 읽었어야합니다. 그래서 아마 테이블 헤더 일 겁니다. –

답변

1

나는 생각한다, 당신은이를 넣어해야합니다

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

을의 첫 번째 줄에 루프

당신은 각 temparray에 대한 새 연락처를 삽입해야
+0

그리고 일단 이것을했다면 for 루프 밖에서'[newContext save : & error];를 써라. –

+0

감사합니다 :-) 나는 너무 행복합니다! –

0

을 위해. 따라서 newContact = [NSEntityDescription insertNewObjectForEntityForName:@"Contacts" inManagedObjectContext:newContext];을 for로 이동해야합니다.

+0

감사합니다 !!! 나는 그것을 해결했다! Diziet 때문에 ... –

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

T^T <- 이것은 인상적인 이모티콘 .. 당신은 매우 천재적입니다. 고맙습니다!!!!!!!!!! –