当我使用 Core Data 在我的 iOS 应用程序中保存数据时遇到问题。
我的应用程序可以在一秒钟内从服务器接收许多文本消息。
所以我需要将这些消息保存在我的数据库中,现在我在队列中使用 NSOperations 来保存消息(所以你可以想象 NSOperationQueue 中的 NSOperation 的数量)。
问题是在一些指令之后,我阻止了 NSOperationQueue 并且 NSOperation 的数量无限制地增加。
经过一番调查,我发现问题出在保存上下文上,保存上下文阻塞了 NSOperation 并且 NSOperation 我永远不会结束,也永远不会出队,但我无法解决它。
这是我的 NSOperation 代码:
@interface SaveRecievedMessageOperation()
@property (nonatomic, strong) NSManagedObjectContext *managedObjectContext;
@property (nonatomic, strong) AppDelegate *appdelegate;
@property (nonatomic, assign) BOOL executing;
@property (nonatomic, assign) BOOL finished;
@end
@implementation SaveRecievedMessageOperation
@synthesize message;
@synthesize managedObjectContext;
@synthesize appdelegate;
@synthesize executing;
@synthesize finished;
- (id)initWithMessage:(SipMessage *)messageToSave
{
if (self = [super init]) {
self.message = messageToSave;
}
return self;
}
- (void)main
{
@autoreleasepool
{
self.appdelegate = [[UIApplication sharedApplication] delegate];
[self managedObjectContext];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(mergeChanges:)
name:NSManagedObjectContextDidSaveNotification
object:self.managedObjectContext];
[self saveMessage];
}
}
- (NSManagedObjectContext *)managedObjectContext
{
if (managedObjectContext != nil)
{
return managedObjectContext;
}
NSPersistentStoreCoordinator *coordinator = [self.appdelegate persistentStoreCoordinator];
if (coordinator != nil) {
managedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
[managedObjectContext setPersistentStoreCoordinator:coordinator];
[managedObjectContext setMergePolicy:NSOverwriteMergePolicy];
}
return managedObjectContext;
}
- (void)saveMessage
{
NSDictionary *header = self.message.headers;
NSArray *bodies = self.message.bodies;
SipBody *sipBody;
NSDictionary* body;
NSData *ContentData;
if ([[header valueForKey:@"Content-Type"] rangeOfString:@"application/json"].location != NSNotFound)
{
sipBody = [bodies objectAtIndex:0];
body = [NSJSONSerialization
JSONObjectWithData:sipBody.content
options:NSJSONReadingAllowFragments
error:nil];
}
else if ([[header valueForKey:@"Content-Type"] rangeOfString:@"multipart/mixed"].location != NSNotFound)
{
for (SipBody *sipB in bodies) {
if ([[sipB.headers valueForKey:@"Content-Type"] rangeOfString:@"application/json"].location != NSNotFound)
{
body = [NSJSONSerialization
JSONObjectWithData:sipB.content
options:NSJSONReadingAllowFragments
error:nil];
}
else
{
ContentData = [NSData dataWithData:sipB.content];
}
}
}
else
{
return;
}
MGMPhone *sender;
NSArray *senders = [self updatePhonesFromMSISDNsList:[[header valueForKey:@"swfrom"] componentsSeparatedByString:MGMseparator]];
sender = senders[0];
NSError *error;
MGMMessage *aMesage = [MGMMessage createInContext:self.managedObjectContext];
[aMesage setBoxType:[NSNumber numberWithInteger:BoxTypeIncomingMessage]];
[aMesage setContent:[body valueForKey:@"Content"]];
[aMesage setContentType:[header valueForKey:@"Content-Type"]];
[aMesage setGroupMessage:( [[header valueForKey:@"groupmessage"] isEqualToString:@"true"]
?
[self saveContext];
}
#pragma mark core data
- (void)mergeChanges:(NSNotification *)notification
{
dispatch_async(dispatch_get_main_queue(), ^{
NSManagedObjectContext *mainContext = [appdelegate managedObjectContext];
[mainContext performSelector:@selector(mergeChangesFromContextDidSaveNotification:) withObject:notification];
[self setManagedObjectContext:nil];
}
- (void)saveContext
{
NSError *error = nil;
if (self.managedObjectContext != nil)
{
if ([self.managedObjectContext hasChanges]) {
BOOL isSaved = [self.managedObjectContext save:&error];
if(!isSaved){
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
}
else if (![self.managedObjectContext hasChanges]){
[self setManagedObjectContext:nil];
}
}
}
@end
这是一个共享实例。
#import "CoreDataService.h"
static CoreDataService *sharedService = nil;
@implementation CoreDataService
@synthesize coreDataReceptionQueue;
+ (id)sharedService
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
if (sharedService == nil) sharedService = [[self alloc] init];
});
return sharedService;
}
- (NSOperationQueue*) coreDataReceptionQueue
{
if (coreDataReceptionQueue)
{
return coreDataReceptionQueue;
}
coreDataReceptionQueue = [[NSOperationQueue alloc] init];
[coreDataReceptionQueue setMaxConcurrentOperationCount:1];
return coreDataReceptionQueue;
}
@end
这就是我添加新操作的方式
SaveRecievedMessageOperation *op = [[SaveRecievedMessageOperation alloc]initWithMessage:message];
[[[CoreDataService sharedService] coreDataReceptionQueue] addOperation:op];