在iOS 12中,不建议使用archiveRootObject:toFile:。有人能建议一种简化的替代方法来将对象归档到文件吗?
c.execute("""SELECT num from tb_numbers""")
table = c.fetchall()
x = 1
for each_value in table:
if each_value[0] == x:
print("Yeah! Find: {0}".format(each_value[0]))
答案 0 :(得分:6)
与suggested by Apple一样,我们应该使用 FileManager 读取/写入存档文件。
guard let documentURL = FileManager().urls(for: .documentDirectory, in: .userDomainMask).first else { return }
let filePath = "MyArchive.data"
let fileURL = documentURL.appendingPathComponent(filePath)
// Archive
if let dataToBeArchived = try? NSKeyedArchiver.archivedData(withRootObject: myObject, requiringSecureCoding: true) {
try? dataToBeArchived.write(to: fileURL)
}
// Unarchive
if let archivedData = try? Data(contentsOf: fileURL),
let myObject = (try? NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(archivedData)) as? Object {
/// Do anything with the unarchived object
///
///
}
答案 1 :(得分:3)
感谢@vadian的提示,以下是我想在iOS 12下进行归档和取消归档的内容:
NSError *error = nil;
NSString *docsDir;
NSArray *dirPaths;
//Get the device's data directory:
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = [dirPaths objectAtIndex:0];
NSString *databasePath = [[NSString alloc] initWithString: [docsDir stringByAppendingPathComponent:@"appData.data"]];
//Archive using iOS 12 compliant coding:
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:@"foo" requiringSecureCoding:NO error:&error];
[data writeToFile:databasePath options:NSDataWritingAtomic error:&error];
NSLog(@"Write returned error: %@", [error localizedDescription]);
//Unarchive the data:
NSData *newData = [NSData dataWithContentsOfFile:databasePath];
NSString *fooString = [NSKeyedUnarchiver unarchivedObjectOfClass:[NSString class] fromData:newData error:&error];
答案 2 :(得分:2)
替换为archivedDataWithRootObject:requiringSecureCoding:error:
+ (NSData *)archivedDataWithRootObject:(id)object
requiringSecureCoding:(BOOL)requiresSecureCoding
error:(NSError * _Nullable *)error;
加上额外的步骤将数据写入磁盘。
答案 3 :(得分:0)
unArchivedObjectOfClass在尝试对不使用安全编码的对象进行解码时为我抛出了一个错误。经过多次试验和错误,这才是最终有效的方法,而没有触发iOS 12/13弃用警告:
// Archive the object
NSData* data = [NSKeyedArchiver archivedDataWithRootObject:theObject requiringSecureCoding:NO error:nil];
// Unarchive the object
NSKeyedUnarchiver* unarchiver = [[NSKeyedUnarchiver alloc] initForReadingFromData:data error:nil];
unarchiver.requiresSecureCoding = NO;
id theCopy = [unarchiver decodeTopLevelObjectForKey:NSKeyedArchiveRootObjectKey error:nil];