大家晚上好,sqlite 能够保存对象吗,如果不行,那么怎么查出来再转为模型呢?
黄舟2017-04-18 09:49:39
Of course objects can be saved. . . Sqlite is a lightweight database. . If you use Sqlite, you can only find the data and then alloc the OC object and then assign it. . . If you want to achieve automation, you can consider CoreData
阿神2017-04-18 09:49:39
It can be saved. If it were me, I would use JSON to transfer it. When it is entered into the database, it will be a JSON string, and when it is taken out, it will be transferred to the object. Others are also available, it depends on your preference.
If you want to save trouble, you can use Realm to directly access objects. Of course there are shortcomings and pitfalls. We have been using it in a production environment for 2 years
黄舟2017-04-18 09:49:39
You can use fmdb to find the data and convert it into a dictionary array, and then convert the dictionary into a model. This is how I usually do it
NSMutableArray* collectedFood = [NSMutableArray array];
FMDatabase* dataBase = [FMDatabase databaseWithPath:[self dbPath]];
BOOL open = [dataBase open];
if (open) {
NSString* selectSql = @"select * from foodCollection order by id desc";
FMResultSet* result = [dataBase executeQuery:selectSql];
while (result.next) {
YYFoodModel* foodModel = [[YYFoodModel alloc] init];
foodModel.id = [result stringForColumn:@"foodId"];
foodModel.name = [result stringForColumn:@"name"];
foodModel.pic = [result stringForColumn:@"pic"];
NSData* data = [result dataForColumn:@"measure"];
foodModel.measure = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
foodModel.cal = [result stringForColumn:@"cal"];
foodModel.calOfPerG = [result doubleForColumn:@"calOfPerG"];
foodModel.util = [result stringForColumn:@"util"];
foodModel.calOfUtil = [result stringForColumn:@"calOfUtil"];
foodModel.cnt = [result stringForColumn:@"cnt"];
foodModel.food_measure = [result stringForColumn:@"food_measure"];
foodModel.food_cal = [result stringForColumn:@"food_cal"];
foodModel.checked = [result stringForColumn:@"checked"];
foodModel.remark = [result stringForColumn:@"remark"];
foodModel.desc_url = [result stringForColumn:@"desc_url"];
[collectedFood addObject:foodModel];
}
[dataBase close];
}
return collectedFood;
高洛峰2017-04-18 09:49:39
Use realm, oo database, sqlite is a little troublesome and requires Model and DB to convert each other. But swift does not support reflection, so you either have to write the conversion process by hand, or the Model inherits NSObject