IOS 如何持久化自定义对象 2014-08-01 01:38

如果持久话自定义对象 那么这个对象一定要遵循 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 对象的键值对

猜你喜欢

转载自www.cnblogs.com/lu-ping-yin/p/10992764.html
今日推荐