Archiving Objective-C Objects with NSCoding

For the seasoned Cocoa developer, this is a piece of cake. For newer developers, this can be a real pain, especially if you don’t know what you’re looking for. I get this question a decent amount, so I figured I’d put a quick guide together.

The Problem

You can’t put just any object in a plist. This mainly gets people when they want to put something into NSUserDefaults and get an error (because NSUserDefaults archives to a plist under the hood).

Plists only support the core types: NSString, NSNumber, NSDate, NSData, NSArray, NSDictionary (and their CF buddies thanks to the toll-free bridge). The key here is NSData. You can convert any object to NSData with the NSCoding protocol.

The Solution

There are two things you have to do: implement NSCoding and then use the archiver and unarchiver.

Implementing NSCoding

Say you have an object that looks like this:

@interface Note : NSObject {
NSString *title;
NSString *author;
BOOL published;
} @property (nonatomic, copy) NSString *title;
@property (nonatomic, copy) NSString *author;
@property (nonatomic) BOOL published; @end
#import "Note.h"

@implementation Note

@synthesize title;
@synthesize author;
@synthesize published; - (void)dealloc {
[title release];
[author release];
[super dealloc];
} @end

Pretty simple, right?

Now, all you have to do to implement NSCoding is the following:

@interface Note : NSObject <NSCoding> {
NSString *title;
NSString *author;
BOOL published;
} @property (nonatomic, copy) NSString *title;
@property (nonatomic, copy) NSString *author;
@property (nonatomic) BOOL published; @end
#import "Note.h"

@implementation Note

@synthesize title;
@synthesize author;
@synthesize published; - (void)dealloc {
[title release];
[author release];
[super dealloc];
} - (id)initWithCoder:(NSCoder *)decoder {
if (self = [super init]) {
self.title = [decoder decodeObjectForKey:@"title"];
self.author = [decoder decodeObjectForKey:@"author"];
self.published = [decoder decodeBoolForKey:@"published"];
}
return self;
} - (void)encodeWithCoder:(NSCoder *)encoder {
[encoder encodeObject:title forKey:@"title"];
[encoder encodeObject:author forKey:@"author"];
[encoder encodeBool:published forKey:@"published"];
} @end

Pretty simple. All I did was add the <NSCoding> protocol delectation in the header file and initWithCoder: and encodeWithCoder: in the implementation. You use these methods to tell NSCoder how to encode your object into data. Notice how two of the variables are objects and one was a BOOL. You have to use different methods for non-objects. The NSCoder documentation has the full list.

Remember, that you can use NSCoder to archive your object however whatever you want. It doesn’t have to just be all of the instance variables in your object, although that’s what you’ll do 90% of the time.

Using the Archiver and Unarchiver

This part is also really easy. Let’s say you have an array of notes that you want to put into NSUserDefaults, here’s the code:

// Given `notes` contains an array of Note objects
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:notes];
[[NSUserDefaults standardUserDefaults] setObject:data forKey:@"notes"];

Unarchiving is just as easy:

NSData *notesData = [[NSUserDefaults standardUserDefaults] objectForKey:@"notes"];
NSArray *notes = [NSKeyedUnarchiver unarchiveObjectWithData:notesData];

用NSCoding协议完成“编码/解码”操作-Object-C的更多相关文章

  1. java中文乱码解决之道(五)-----java是如何编码解码的

    在上篇博客中LZ阐述了java各个渠道转码的过程,阐述了java在运行过程中那些步骤在进行转码,在这些转码过程中如果一处出现问题就很有可能会产生乱码!下面LZ就讲述java在转码过程中是如何来进行编码 ...

  2. java中文乱码解决之道(六)-----javaWeb中的编码解码

    在上篇博客中LZ介绍了前面两种场景(IO.内存)中的java编码解码操作,其实在这两种场景中我们只需要在编码解码过程中设置正确的编码解码方式一般而言是不会出现乱码的.对于我们从事java开发的人而言, ...

  3. java中文乱码解决之道(六)—–javaWeb中的编码解码

    在上篇博客中LZ介绍了前面两种场景(IO.内存)中的java编码解码操作,其实在这两种场景中我们只需要在编码解码过程中设置正确的编码解码方式一般而言是不会出现乱码的.对于我们从事java开发的人而言, ...

  4. java中文乱码解决之道(五)—–java是如何编码解码的

    原文出处:http://cmsblogs.com/?p=1491 在上篇博客中LZ阐述了java各个渠道转码的过程,阐述了java在运行过程中那些步骤在进行转码,在这些转码过程中如果一处出现问题就很有 ...

  5. java是如何编码解码的

    在上篇博客中LZ阐述了java各个渠道转码的过程,阐述了java在运行过程中那些步骤在进行转码,在这些转码过程中如果一处出现问题就很有可能会产生乱码!下面LZ就讲述java在转码过程中是如何来进行编码 ...

  6. url参数的编码解码Demo

    为了保证在页面传递数据的安全性,我们通常会对Url传递的参数进行编码解码操作.我们写一个Demo剖析URL编码解码过程. 完整Demo下载地址 1. Url参数如何在服务端进行编码和解码. 1.1 U ...

  7. 第57节:Java中流的操作以及编码解码

    我的博客: https://huangguangda.cn/ https://huangguangda.github.io/ 前言: 编码解码:编码时将信息从一种形式变成为另一种形式,成为编码.编码为 ...

  8. day8_文件操作及编码解码

    一.文件操作基本流程 计算机系统分为:计算机硬件,操作系统,应用程序三部分. 我们用python或其他语言编写的应用程序若想要把数据永久保存下来,必须要保存于硬盘中,这就涉及到应用程序要操作硬件,众所 ...

  9. python基础3之文件操作、字符编码解码、函数介绍

    内容概要: 一.文件操作 二.字符编码解码 三.函数介绍 一.文件操作 文件操作流程: 打开文件,得到文件句柄并赋值给一个变量 通过句柄对文件进行操作 关闭文件 基本操作: #/usr/bin/env ...

随机推荐

  1. humans.txt学习理解

    可以通过以下链接访问到Google的humans.txt https://www.google.com/humans.txt 百度上有关于humans.txt的介绍 http://baike.baid ...

  2. 如何将excel中的一个表格内容转成xml格式的文件

    转自:http://www.cnblogs.com/sansi/archive/2012/02/06/2340471.html 感谢作者,解决了折磨我几天的问题,顿时心情开朗~ ----------- ...

  3. 洛谷 - P2551 - 华夏60战斗机 - 简单dp

    https://www.luogu.org/problemnew/show/P2551 首先这道题没有给Hm的最大值,很坑,只能随便开一个100没想到还过了. 观察题目,发现虽然高度可以变化,但是速度 ...

  4. 718. Maximum Length of Repeated Subarray

    Given two integer arrays A and B, return the maximum length of an subarray that appears in both arra ...

  5. LightOJ1197【数学】

    引自:WONTER 题意: 给你两个数,a,b,让你求区间[a,b]里面有多少个素数: 思路: 首先要知道,我们要想筛 [1, b] 中所有的素数,只需要用到 [1, sqrt(b)] 中的所有素数来 ...

  6. Root Motion深度解析[Unity]

    http://blog.csdn.net/cubesky/article/details/39478207 在很多动画当中,模型的位置.角度往往会发生变化,我们需要决定是否将模型再动画中发生的这些变换 ...

  7. poj2133(sg函数)

    关于sg函数:http://www.cnblogs.com/Knuth/archive/2009/09/05/1561007.html 题目链接:http://poj.org/problem?id=2 ...

  8. 洛谷P2568 GCD(莫比乌斯反演)

    传送门 这题和p2257一样……不过是n和m相同而已…… 所以虽然正解是欧拉函数然而直接改改就行了所以懒得再码一遍了2333 不过这题卡空间,记得mu开short,vis开bool //minamot ...

  9. ajax请求过程

    1.什么是ajax AJAX=Asynchronous JavaScript and XML  =====>异步的javascript和xml AJAX是在不重新加载整个页面的情况下与服务器交换 ...

  10. 第二十一篇 .NET高级技术之使用多线程(三)

    1.  单元模式和Windows Forms 单元模式线程是一个自动线程安全机制, 非常贴近于COM——Microsoft的遗留下的组件对象模型.尽管.NET最大地放弃摆脱了遗留下的模型,但很多时候它 ...