1. 程式人生 > >Sqlite 儲存自定義物件

Sqlite 儲存自定義物件

在iOS中如果想儲存自定義物件,要讓自定義物件實現NSCoding介面並實現方法-(id)initWithCoder:(NSCoder *)coder-(void)encodeWithCoder:(NSCoder *)coder;

@interface RegUserInfo : NSObject <NSCoding>   
@property (nonatomic, strong) NSString *siteName;
@end  
@@implementation RegUserInfo
-(void) encodeWithCoder:(NSCoder *)encoder  {  
    [encoder encodeObject:siteName forKey:@"siteName"];  
} 
-(id) initWithCoder:(NSCoder *)decoder {  
    siteName = [decoder decodeObjectForKey:@"siteName"];    
    return self;  
}  
//兩個方法中的key必須一致
@end

如果專案中使用了mjextention,可以直接在.m檔案中呼叫MJCodingImplementation


@interface MarkerUniformConfig : NSObject<NSCoding>//需要繼承NSCoding
@property(nonatomic,strong)NSString* icon_id;
@end


@implementation MarkerUniformConfig
MJCodingImplementation//這裡會自動完成屬性序列化過程
@end