Sqlite 儲存自定義物件
阿新 • • 發佈:2019-01-09
在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