2017-01-23 6 views
0

코어 데이터 개체를 저장하기 위해 하위 컨텍스트를 사용하고 있지만 저장하지 않습니다. 이 코드의 문제점은 무엇입니까? perform 블록을 제거하고 performblockAndwait도 사용했지만 작동하지는 않았습니다. prepareDataForCustomYearlyOption 메소드와 마찬가지로 나는 다른 사람들에게 일일, 주간, 월간 세 가지 더 많은 메소드를 아래 코드와 거의 동일하게 사용한다.하위 컨텍스트가 코어 데이터에 저장되지 않음

다른 곳에서도 동일한 코드가 작동합니다.

- (NSManagedObjectContext *)backgroundManagedObjectContext 
{ 
    if (_managedObjectContext == nil) { 
     [[OUCSCoreDataManager privateInstance]managedObjectContext]; 
    } 
    NSManagedObjectContext *temporaryContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType]; 
    temporaryContext.parentContext = _managedObjectContext; 
    return temporaryContext; 
} 
- (void)prepareDataForCustomYearlyOption { 

    if ([CoreDataManager countForEntity:kCALENDAR_CUSTOM_YEARLY_REPEAT_OPTIONS] != 0) { 
     return; 
    } 

    NSManagedObjectContext *temporaryContext = [[CoreDataManager privateInstance]backgroundManagedObjectContext]; 

    [temporaryContext performBlock:^{ 
     @try { 
      RepeatOptionsCustomYearly *yearlyOption = [RepeatOptionsCustomYearly insertInManagedObjectContext:temporaryContext]; 
      yearlyOption.title = NSLocalizedString(k_Yearly, @"REPEAT_OPTIONS_TITILE3"); 
      yearlyOption.isSelected = [NSNumber numberWithBool:NO]; 
      yearlyOption.every = [NSNumber numberWithInt:1]; 
      yearlyOption.startOn = [NSDate date]; 
      yearlyOption.endsOn = [NSDate date]; 
      yearlyOption.neverEnds = [NSNumber numberWithBool:NO]; 
      yearlyOption.summary = @""; 
      yearlyOption.everyRange = [NSKeyedArchiver archivedDataWithRootObject:[self getYearRange]]; 

     } @catch (NSException *exception) { 
      NSLog(@"Calendar Manager Exception: --> %@ %@",exception.name, exception.reason); 
     } 
     // push to parent 
     [temporaryContext performBlock:^{ 
      // push to parent 
      NSError *errorTemp; 
      if (![temporaryContext save:&errorTemp]) 
      { 
       // handle error 
       NSLog(@"Temp MOC Save Error: %@",errorTemp.description); 
      } 
     }]; 

    }]; 
} 

답변

0

코드에 두 가지 문제가 있다고 가정합니다.

첫 번째 것은 backgroundManagedObjectContext 방법 안에 있습니다. 바르 _managedObjectContext가 설정되지 않습니다 :

- (NSManagedObjectContext *)backgroundManagedObjectContext 
{ 
    if (_managedObjectContext == nil) { 
     _managedObjectContext = [[OUCSCoreDataManager privateInstance]managedObjectContext]; 
    } 
    NSManagedObjectContext *temporaryContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType]; 
    temporaryContext.parentContext = _managedObjectContext; 
    return temporaryContext; 
} 

두 번째는 두 번 performBlock 전화 일 수 있었다 :

- (void)prepareDataForCustomYearlyOption { 

    if ([CoreDataManager countForEntity:kCALENDAR_CUSTOM_YEARLY_REPEAT_OPTIONS] != 0) { 
     return; 
    } 

    NSManagedObjectContext *temporaryContext = [[CoreDataManager privateInstance]backgroundManagedObjectContext]; 

    [temporaryContext performBlock:^{ 
     @try { 
      RepeatOptionsCustomYearly *yearlyOption = [RepeatOptionsCustomYearly insertInManagedObjectContext:temporaryContext]; 
      yearlyOption.title = NSLocalizedString(k_Yearly, @"REPEAT_OPTIONS_TITILE3"); 
      yearlyOption.isSelected = [NSNumber numberWithBool:NO]; 
      yearlyOption.every = [NSNumber numberWithInt:1]; 
      yearlyOption.startOn = [NSDate date]; 
      yearlyOption.endsOn = [NSDate date]; 
      yearlyOption.neverEnds = [NSNumber numberWithBool:NO]; 
      yearlyOption.summary = @""; 
      yearlyOption.everyRange = [NSKeyedArchiver archivedDataWithRootObject:[self getYearRange]]; 

     } @catch (NSException *exception) { 
      NSLog(@"Calendar Manager Exception: --> %@ %@",exception.name, exception.reason); 
     } 
     // push to parent 
     // Comment this ->[temporaryContext performBlock:^{ 
      // push to parent 
      NSError *errorTemp; 
      if (![temporaryContext save:&errorTemp]) 
      { 
       // handle error 
       NSLog(@"Temp MOC Save Error: %@",errorTemp.description); 
      } 
     // Comment this -> }]; 

    }]; 
} 

가 필요한 경우 temporaryContext의 부모 컨텍스트에 저장하는 것을 잊지 마십시오.

+0

_managedObjectContext이있는 개인 큐를 사용하는 올바른 방법을 주요 컨텍스트를 갱신해야한다, 그건 초기화 중입니다. 나는 perform 블록을 제거하려고했지만 작동하지 않습니다. – Sandy

+0

저장 작업 중에 오류가 있습니까? – yageek

1

당신이 뭔가를 시도 할 수 있지만, 오류 처리가 따라야 할 예되지 않습니다 :

은 당신이 당신의 개인 큐의 주요 문맥에 올바르게 설정 얻을합니다.

func getPrivateQueueMOC() -> NSManagedObjectContext? 
{ 
    if let moc = delegate.managedObjectContext 
    { 
     let privateMOC = NSManagedObjectContext(concurrencyType: NSManagedObjectContextConcurrencyType.privateQueueConcurrencyType) 
     privateMOC.parent = moc 
     return privateMOC 
    } 

    return nil 
} 

이 변경 사항을 저장하고 가능한 한 빨리

func savePrivateContext(privateContext:NSManagedObjectContext) 
{ 
    do { 
     try privateContext.save() 

     guard let moc = delegate.managedObjectContext else { return } 
     moc.performAndWait { 
      do { 
       try moc.save() 
      } catch { 
       fatalError("Failure to save context: \(error)") 
      } 
     } 
    } catch { 
     fatalError("Failure to save context: \(error)") 
    } 
} 

func persistStuff(_ stuff:[Dictionary<String, AnyObject>]) 
{ 
    if stuff.isEmpty 
    { 
     return 
    } 

    if let context = getPrivateQueueMOC() 
    { 
     context.perform({() -> Void in 
      // Do your stuff here 

      if context.hasChanges 
      { 
       self.savePrivateContext(privateContext: context) 
      } 

      DispatchQueue.main.async(execute: {() -> Void in 
       // Tell UI to update 
      }) 
     }) 
    } 
}