2011-03-06 5 views
0

아이폰 앱을 쓰고 있습니다. 영구 저장소에 데이터를 저장해야하지만 문제가 발생합니다 ... xcdatamodel에서 엔터티를 만들었으며 내 특성에 대한 기본값을 가져 오는 데 문제가 없습니다. 필자의 테스트에서 아래의 코드를 몇 차례 살펴보고 응용 프로그램이 활성화되어있는 동안이 속성 (정수)을 변경할 수 있습니다. 그러나 닫고 응용 프로그램을 다시 열 때 내 정수 (myInt) 내가 그것을 업데이트 한 마지막 값이 될 것으로 예상했을 때 기본값으로 돌아갑니다. 여기 내가 뭐하는 거지입니다 : 그 라인을 기대했다영구 저장 iphone에 저장하는 데 문제가 있습니다.

NSManagedObjectContext *managedObjectContext = appDelegate.managedObjectContext; 
NSEntityDescription *myTestEntity = [NSEntityDescription 
             entityForName:@"TestEntity" 
             inManagedObjectContext:managedObjectContext]; 

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; 

[fetchRequest setEntity:timeStampEntity]; 

NSError *error = nil; 
NSArray *fetchedObjects = [managedObjectContext executeFetchRequest:fetchRequest error:&error]; 
if (fetchedObjects == nil) { 
    // TODO: Handle the error 
} 
for (id oneObject in fetchedObjects) 
{ 
    NSInteger myInt = [[oneObject valueForKey:@"myStoredInt"]intValue]; 
    myInt++; 
    [oneObject setValue:[NSNumber numberWithInt: myInt] forKey:@"myStoredInt"]; 
    NSError *error = nil; 
    if (![managedObjectContext save:&error]) {//TODO: Handle error  
    } 
} 

[fetchRequest release]; 

:

if (![managedObjectContext save:&error]) 

이 일을하고 영구 저장소에 변경 사항을 저장하는 것입니다,하지만 그것을하지 않습니다! (for 루프 내부 또는 외부에이 줄이 있으면 결과가 바뀌지 않습니다.) 내가 뭘 잘못하고 있니?

도움 주셔서 감사합니다.

답변

3

앱 위임 코드를 표시 할 수 있다면 도움이 될 것입니다. 내 추측은 어딘가에 당신이 데이터를 자신을 재설정하고 있다는 것입니다. 어쩌면 당신이 시작 데이터를로드하는 방법. 지금은

3 노트 :

  1. 당신은 루프 내부의 저장 방법을 배치 할 필요가 없습니다. 당신은 모든 변경이 이고 한 번만 만들어진 후에 을 배치해야합니다. (추가되지 않은 경우) 당신이에 저장 방법을 호출 한 경우
  2. 검사 :

    - (void)applicationWillTerminate:(UIApplication*)application { 
         [self saveContext]; 
        } 
    
        - (void)applicationDidEnterBackground:(UIApplication*)application { 
        [self saveContext]; 
        } 
    
  3. 이 앱의 모든 점심 기본값을로드하는 경우 보려고 도움이되지 복용량 경우 .

행운을 빕니다

하고

편집

안녕을 환영합니다, 당신은 그렇게 할 수 -

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator { 

    if (persistentStoreCoordinator_ != nil) { 
     return persistentStoreCoordinator_; 
    } 

    NSURL *storeURL = [NSURL fileURLWithPath: [[self applicationDocumentsDirectory]            stringByAppendingPathComponent: @"anyname.sqlite"]]; 

    //check if the store already exist? 
    BOOL firstRun = NO; 
    if (![[NSFileManager defaultManager] fileExistsAtPath:[storeURL path] isDirectory:NULL]) { 
     firstRun = YES;  
    } 

    NSError *error = nil; 
    persistentStoreCoordinator_ = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]]; 
    if (![persistentStoreCoordinator_ addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) { 

     NSLog(@"Unresolved error %@, %@", error, [error userInfo]); 
     abort(); 
    }  

    if(firstRun){ 
     //add your default data here 
    } 
} 
+0

샤니을, 정말 감사합니다! 당신은 내 응용 프로그램 델리게이트에서 옳았습니다. 매번 객체를 시작했습니다. [NSEntityDescription insertNewObjectForEntityForName : @ "TestEntity inManagedObjectContext : managedObjectContext]; 초심자라고 말할 수 있습니다. 이 작업을 한 번만하고 싶습니다. 이미 수행했는지 어떻게 알 수 있습니까? 고마워요! – san

+0

안녕하세요. 나는 나의 대답을 편집했다. – shannoga

+0

이것은 Shani입니다! 내가 원했던 것처럼 작동합니다. 정말 고맙습니다. – san