我有一个单例延迟事务管理器类,它负责将由于各种因素(网络可达性、邻近性等)而无法完成的 iphone 到应用程序服务器的事务入队和出队。当可达性/邻近性恢复时,它会尝试使事务出队。另一个事务也可能在出队发生的同时被入队。
我的理解是 NSUserDefaults 是可变字典SO 链接的线程安全包装器,这正是我想要的。相同的 SO 链接认为 NSUserDefaults 是针对用户偏好的。
这些交易不是用户偏好,但这是我想要的功能。所以,这里的问题是,我可以在 NSUserDefaults 中读取/写入/同步事务的 NSMutableDictionary 而不会损坏字典,还是需要通过 NSKeyed(Un)Archiver 读取和写入来实现自己的锁定机制(见下文)?
一些代码:
- (void) queThing:(Thing *)aThing {
// @synchronized this block?
NSMutableDictionary * QD = [self readFile];
[QD setObject:aThing forKey:aThing.thingId];
[self writeFile: QD];
// @ sync?
}
- (void) writeFile:(NSMutableDictionary *)theData {
BOOL status = [NSKeyedArchiver archiveRootObject: theData toFile:archivePath];
if ( !status) {
DebugLog(@"Write to archive failed.");
} else {
DebugLog(@"Write to archive SUCCEEDED.");
}
}
- (NSMutableDictionary *) readFile {
NSMutableDictionary *Q =[NSKeyedUnarchiver unarchiveObjectWithFile:archivePath];
if ( ! Q ) {
Q = [NSMutableDictionary dictionaryWithCapacity:2];
}
return Q;
}
出队:
// @synchronized this block?
NSMutableDictionary * QD = [self readFile];
[QD removeObjectForKey:thing.thingId];
[self writeFile: QD];
// @ sync?