sqlite只支持一些基本类型的存储(如TEXT,INTEGER,BLOB,REAL),但OC对象肯定无法直接通过存储sqlite中。
当然可以通过nskeyedarchiver进行归档,下面会介绍如何把OC对象存入sqlite的方法。话不多说:
一、把对象存入sqlite中
1、把对象转换成字典
id obj;
NSMutableDictionary *dic = [NSMutableDictionary dictionary];
unsigned int propsCount;
objc_property_t *props = class_copyPropertyList([obj class], &propsCount);
for(int i = 0;i < propsCount; i++)
{
objc_property_t prop = props[i];
NSString *propName = [NSString stringWithUTF8String:property_getName(prop)];
if ([propName hasSuffix:@"Url"]) {
continue;
}
id value = [obj valueForKey:propName];
if(value == nil)
{
value = [NSNull null];
}
else
{
value = [self getObjectInternal:value];
[dic setObject:value forKey:propName];
}
}
free(props);
return dic;
2、把字典转换成字符串存储
NSError *error = nil;
NSData *result = [NSJSONSerialization dataWithJSONObject:dic options:kNilOptions error:&error];
NSString *jsonString = [[NSString alloc] initWithData:result encoding:NSUTF8StringEncoding];
最后把字符串存储到sqlite中。
二、从sqlite中取出对象
1、取出转换成NSDictionary
NSString *str = [rs stringForColumn:@"***"];
NSData* data = [str dataUsingEncoding:NSUTF8StringEncoding];
__autoreleasing NSError* error = nil;
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
2、从NSDictionary转换为OC对象
id obj = [[[obj class] alloc] init];
if (dict) {
for (NSString *key in [dict keyEnumerator]) {
if([key isEqualToString:@"***"]){
obj.*** = [[keyedValues objectForKey:@"***"] intValue];
}else if([key isEqualToString:@"***"]){
obj.*** = [[keyedValues objectForKey:@"***"] boolValue];
}
}
}