---
title: "[ios]NSUserDefault保存自定义object问题"
author: "119568242"
date: "2013-04-25T21:25:56Z"
tags: []
categories: ["移动开发"]
slug: "ios-nsuserdefault-object"
draft: false
lastmod: "2013-04-25T21:25:56Z"
id: 1853802
url: "https://poolo.iteye.com/blog/1853802"
---

NSUserDefault 

的setObject 只能对少数 NSString等少数非自定义对象保存。

那么如果要保存自定义对象则需要。

使用\[NSKeyedArchiver archivedDataWithRootObject:]归档以下将对象封装成NSData，再使用NSUserDefault保存。

使用时需要解压缩unarchiveObjectWithData

 

demo:

+(id)highImage{

    NSData* data = \[\[NSUserDefaultsstandardUserDefaults] objectForKey:@"higt\_image"];

    id image= \[NSKeyedUnarchiverunarchiveObjectWithData:data];

    NSLog(@"image!:%@",image);

    if(image){

        return image;

    }

    return \[UIImageimageNamed:@"Default.png"];

}

+(void)setHighImage:(UIImage\*)image{

    NSLog(@"image!:%@",image);

    NSData* data=\[NSKeyedArchiverarchivedDataWithRootObject:image];

    \[\[NSUserDefaultsstandardUserDefaults] setObject:data forKey:@"higt\_image"];

}

 

参考：http://blog.csdn.net/chyroger/article/details/5785297