ios developer tiny share-20161027

今天讲Objective-C的持久化对象,你需要实现NSCoding协议,另外,一些集合类,比如NSArray, NSDictionary, NSString, NSData, NSDate and NSNumber,已经实现了这个协议,意味着这些类已经支持持久化。


下面是ios官方api的文档:

Use Collections to Persist Your Object Graph

The NSArray and NSDictionary classes make it easy to write their contents directly to disk, like this:

NSURL *fileURL = ...
NSArray *array = @[@"first", @"second", @"third"];

BOOL success = [array writeToURL:fileURL atomically:YES];
if (!success) {
	// an error occured...
}

If every contained object is one of the property list types (NSArray, NSDictionary, NSString, NSData, NSDate and NSNumber), it’s possible to recreate the entire hierarchy from disk, like this:

NSURL *fileURL = ...
NSArray *array = [NSArray arrayWithContentsOfURL:fileURL];
if (!array) {
	// an error occurred...
}

For more information on property lists, see Property List Programming Guide.

If you need to persist other types of objects than just the standard property list classes shown above, you can use an archiver object, such as NSKeyedArchiver, to create an archive of the collected objects.

The only requirement to create an archive is that each object must support the NSCoding protocol. This means that each object must know how to encode itself to an archive (by implementing the encodeWithCoder: method) and decode itself when read from an existing archive (the initWithCoder: method).

The NSArray, NSSet and NSDictionary classes, and their mutable subclasses, all support NSCoding, which means you can persist complex hierarchies of objects using an archiver. If you use Interface Builder to lay out windows and views, for example, the resulting nib file is just an archive of the object hierarchy that you’ve created visually. At runtime, the nib file is unarchived to a hierarchy of objects using the relevant classes.

For more information on Archives, see Archives and Serializations Programming Guide.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值