我的应用程序中有一个qrcode扫描功能,每次扫描时,我都必须保存属于一个事件(另一个实体)的扫描记录。所以我获取事件并设置为扫描属性。
问题是:只有保存的第一次扫描才能正确设置事件关系,以下扫描会在没有事件的情况下结束。
这是我目前的架构: ViewController - >服务 - >持久性服务 - > NSManagedObject
Persistence Service层中的所有类都是以下类的子类:
# 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
这就是我保存扫描的方式:
# PseudoLeadPersistenceService.m
-(void) saveOrUpdatePseudoLead:(Lead *)lead ofType:(PseudoLeadType)type {
PseudoLeadDAO *pseudoLeadDAO = [PseudoLeadDAO findPseudoLeadByCode:lead.qrcode.code andEventId:lead.event.idEvent inContext:self.context];
if (pseudoLeadDAO == nil) {
pseudoLeadDAO = [[PseudoLeadDAO alloc] initWithLead:lead andType:type andContext:self.context];
} else {
[pseudoLeadDAO setAttributesWithLead:lead];
}
[self saveContext];
}
在这里我将事件设置在PseudoLeadDAO中(我讨厌这个类名):
# PseudoLeadDAO.m
-(void) setAttributesWithLead:(Lead *)lead {
[self setPseudoLeadID:lead.id];
[self setHotlead:lead.hotlead];
[self setPseudoLeadDescription:lead.description];
[self setEvent:[EventDAO findEventById:lead.event.idEvent inContext:self.managedObjectContext]];
if (lead.qrcode.code != nil) {
[self setQrCode:lead.qrcode.code];
}
}
看起来fetch只对每个上下文或类似的东西工作一次。我真的输了:(