2014-10-30 103 views
1

我的問題的簡短版本:我刪除一個對象,並在我做了一個提取之後返回以前刪除的對象。核心數據獲取已刪除的對象

我下面這個架構: SyncService - >持久性服務 - > NSManagedObject

我所有的持久化服務層類是以下類的子類:

# PersistenceService.h 
#import <Foundation/Foundation.h> 

@interface PersistenceService : NSObject 

@property (nonatomic, retain) NSManagedObjectContext *context; 

-(instancetype) init; 
-(void) saveContext; 
@end 

# PersistenceService.m 
@implementation PersistenceService 

-(instancetype) init { 
    self = [super init]; 

    if (self) { 
     self.context = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType]; 
     self.context.parentContext = [DataManager sharedInstance].managedObjectContext; 
    } 

    return self; 
} 

-(void) saveContext { 
    NSManagedObjectContext *context = self.context.parentContext; 

    [self.context performBlock:^{ 

     NSError *error; 
     [self.context save:&error]; 

     [context performBlock:^{ 
      NSError *error; 
      [context save:&error]; 

      [context.parentContext performBlock:^{ 
       NSError *error; 
       [context.parentContext save:&error]; 

      }]; 
     }]; 
    }]; 

} 

@end 

刪除之前,我在我的主要上下文中取對象:

# Synchronizer.m 
-(void) synchronize { 
    NSArray *pseudoLeads = [[[PseudoLeadPersistenceService alloc] init] getAllParentPseudoLeads]; 
    if (pseudoLeads) { 
     PseudoLeadDAO *pseudoLead = [pseudoLeads objectAtIndex:0]; 
     if ([pseudoLead.type isEqualToNumber:[NSNumber numberWithInt:Capture]]) { 
      CaptureSyncService *service = [[CaptureSyncService alloc] initWithDelegate:self andPseudoLead:pseudoLead]; 
      [service executeRequest]; 
     } else { 
      HotleadSyncService *service = [[HotleadSyncService alloc] initWithDelegate:self andPseudoLead:pseudoLead]; 
      [service executeRequest]; 
     } 
    } 
} 

# PseudoLeadPersistenceService.m 
-(NSArray *) getAllParentPseudoLeads { 
    return [PseudoLeadDAO findAllParentPseudoLeadsInContext:self.context.parentContext]; 
} 

在這裏,我取,在我的子上下文實際刪除對象:

# PseudoLeadPersistenceService.m 
-(void) deletePseudoLeadById:(NSNumber *)pseudoLeadId andEventId:(NSNumber *)eventId { 
    PseudoLeadDAO *pseudoLeadDAO = [PseudoLeadDAO findPseudoLeadById:pseudoLeadId andEventId:eventId inContext:self.context]; 
    [self.context deleteObject:pseudoLeadDAO]; 
    [self saveContext]; 
} 

然後-(void) synchronize再次調用和刪除的對象再次顯示爲故障。在這一點上,我可以根據需要多次獲取並返回。當它再次出現-(void) deletePseudoLeadById:(NSNumber *)pseudoLeadId andEventId:(NSNumber *)eventId方法時,它只會消失,並且會觸發故障。

我會很感激任何幫助。謝謝!

回答

0

問題是併發性。開始保存上下文的線程在下次獲取之前沒有完成。

我解決了使用performBlockAndWait問題:

# PseudoLeadPersistenceService.m 
-(void) deletePseudoLeadById:(NSNumber *)pseudoLeadId andEventId:(NSNumber *)eventId { 
    PseudoLeadDAO *pseudoLeadDAO = [PseudoLeadDAO findPseudoLeadById:pseudoLeadId andEventId:eventId inContext:self.context]; 
    [self.context deleteObject:pseudoLeadDAO]; 
    [self saveContextAndWait]; 
} 
相關問題