有人知道如何在应用程序重启之间将NSOperationQueue持久化到磁盘吗?
有人知道如何在应用程序重启之间将NSOperationQueue持久化到磁盘吗?
这是不可能的。NSOperation是行动,可运行代码的部分,它们通常无法泛化地持久化到磁盘上。
但是,在你的应用程序中,你应该知道将哪些操作添加到了队列中。可以通过子类或者在周围添加一些元数据来实现。然后以自定义的方式存储这些元数据,即关于应该执行什么操作的信息。在应用程序启动时,可以从加载的元数据重新创建之前在队列中的操作。
目前我无法提供更多帮助,但希望这已经有所帮助!
@interface MyOperation : NSOperation<NSCoding>
MyOperation.m
#pragma mark NSCoding
#define kSomeKey @"someKey"
- (void) encodeWithCoder:(NSCoder *)encoder {
[encoder encodeObject:[self someKey] forKey:kSomeKey];
}
- (id)initWithCoder:(NSCoder *)decoder {
if (self = [super init]) {
NSString *someKey = [decoder decodeObjectForKey:kSomeKey];
[self setSomeKey:someKey];
}
return self;
}
Documents/data
文件中,假设你的队列名为 operations
。NSString * const dataPath = @"~/Documents/data";
// private
- (void) serializeQueue {
NSArray* storedOperations = [[self operations] operations];
[NSKeyedArchiver archiveRootObject:storedOperations toFile:[dataPath stringByExpandingTildeInPath]];
}
// private
- (void) deserializeQueue {
NSArray* storedOperations = [NSKeyedUnarchiver unarchiveObjectWithFile:[dataPath stringByExpandingTildeInPath]];
NSLog(@"count of opeations: %lu", (unsigned long) [storedOperations count]);
}