IOS 如何持久化自定义对象(使用NSUserDefaults)

来源:互联网 发布:吉翔数据 编辑:程序博客网 时间:2024/06/05 08:19

如果持久话自定义对象那么这个对象一定要遵循 NSCoding协议并实现编解码;然后再将编解码后的数据 NSKeyedArchiver 到NSData中

@interface NSKeyAndValue : NSObject<NSCoding>// 键值对象@property (nonatomic, retain) NSString* m_strKey;@property (nonatomic, retain) NSString* m_strValue;@property (nonatomic, retain) NSString* m_strID;@end@implementation NSKeyAndValue@synthesize m_strKey,m_strValue, m_strID;- (void)encodeWithCoder:(NSCoder *)aCoder{    [aCoder encodeObject:self.m_strKey forKey:@"m_strKey"];    [aCoder encodeObject:self.m_strValue forKey:@"m_strValue"];    [aCoder encodeObject:self.m_strID forKey:@"m_strID"];}- (id)initWithCoder:(NSCoder *)aDecoder{    self = [super init];    if (self) {        self.m_strKey = [aDecoder decodeObjectForKey:@"m_strKey"];        self.m_strValue = [aDecoder decodeObjectForKey:@"m_strValue"];        self.m_strID = [aDecoder decodeObjectForKey:@"m_strID"];    }    return self;}

读取和保存自定义对象方式如下:

- (void)readMsgDataToMemory{    NSString *key = @"mydata";    NSData *prevSavedData = [[NSUserDefaults standardUserDefaults] objectForKey:key];    NSMutableDictionary *decodedSingleObj = (NSMutableDictionary *)[NSKeyedUnarchiver unarchiveObjectWithData:prevSavedData];    [creatGroupInviterDictionary setDictionary:decodedSingleObj];}- (void)constantStoreOfflineSystemData{    if ([creatGroupInviterDictionary.allKeys count] > 0)    {        NSString *key = @"mydata";        NSData *encodedSingleObj = [NSKeyedArchiver archivedDataWithRootObject:creatGroupInviterDictionary];        [[NSUserDefaults standardUserDefaults] setObject:encodedSingleObj forKey:key];        [[NSUserDefaults standardUserDefaults] synchronize];    }}

creatGroupInviterDictionary 是存储 NSKeyAndValue 对象的键值对

转自:http://lu-ping-yin.blog.163.com/blog/static/416199920147113210728/

0 0
原创粉丝点击