iOS 12.0 替代使用已弃用的 archiveRootObject:toFile: [英] iOS 12.0 Alternative to Using Deprecated archiveRootObject:toFile:
本文介绍了iOS 12.0 替代使用已弃用的 archiveRootObject:toFile:的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在 iOS 12 中,archiveRootObject:toFile: 已被弃用.任何人都可以建议将对象归档到文件的简化替代方案吗?
With iOS 12, archiveRootObject:toFile:has been deprecated. Can anyone suggest a streamlined alternative to archiving objects to a file?
//Generic example of archiver prior to iOS 12.0
-(BOOL) archive:(id)archiveObject withFileName:(NSString*)filename
{
NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
return [NSKeyedArchiver archiveRootObject:archiveObject toFile:path];
}
推荐答案
感谢@vadian 的提示,以下是我在 iOS 12 下进行归档和取消归档的想法:
Thanks to @vadian for the hint, here's what I've come up with to do archiving and unarchiving under 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];
这篇关于iOS 12.0 替代使用已弃用的 archiveRootObject:toFile:的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文