Many apps save the last loaded data when they are off the network, and the most common one they use is the SQLite database, whereFMDBIs also one of the better packaging framework, the following to share the use of FMDB!
- What about downloading and importing frameworks
- Create a management tool class (SQLiteManager) inherits NSObject SQLiteManager. M inside the contents of the following, I write is the class method, you can also write object method, in get a singleton what, write class method is mainly for convenience!
Talk about the background of the project : our data back to the home page is a json, through the framework directly into the dictionary, leadership requirements can preserve only the first page of data, so I don’t have to store all the data according to the field to parse, I is the json data stored directly, also saves after adding new fields in project development, need of database upgrade trouble ~ can only say that I am more lazy ~ nonsense said so much below is the code!!
/// /// @param data // @param page page number + (void)updateHomeData:(NSString *)data page:(NSUInteger)page; // @param page page + (void)insertHomeData:(NSString *)data page:(NSUInteger)page; + (NSArray *)queryHomeData; /// /// @param page page + (void)deleteHomeDataWithPage:(NSInteger)page;Copy the code
3. In the sqlitemanager. h file code is as follows:
// define a global object static FMDatabase *_db; // This method calls + (void)initialize{NSString *documentPath = when calling methods in this class [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]; NSString *dbFilePath = [documentPath stringByAppendingPathComponent:@"homeData.db"]; / / 1. Create the library _db = [FMDatabase databaseWithPath: dbFilePath]; BOOL result = [_db open]; //2. If (result) {// if (result) {// if (result) {// if (result) {// if (result) {//3 executeUpdate:@"create table if not exists t_home(id integer primary key,data text not null,page integer not null);"] ; If (result2) {NSLog(@" create table successfully!!" ); }} // Add data + (void)insertHomeData:(NSString *)data Page :(NSUInteger)page{[_db executeUpdateWithFormat:@"insert into t_home(data,page) values(%@,%ld)",data,page]; } // Update data + (void)updateHomeData:(NSString *)data Page :(NSUInteger) Page {[_db executeUpdateWithFormat:@"update T_HOME set data=%@,page = %ld",data,page]; } // delete data + (void)deleteHomeDataWithPage:(NSInteger)page{[_db executeUpdateWithFormat:@"delete from T_HOME where page = %ld",page]; } // Query data + (NSArray *)queryHomeData{FMResultSet *resultSet = [_db executeQuery:[NSString stringWithFormat:@"select * from t_home"]]; // FMResultSet *resultSet = [_db executeQuery:[NSString stringWithFormat:@"select * from t_home where name LIKE '%%%@%%'",zhangsan]]; NSMutableArray *homeDatas = [NSMutableArray array]; while (resultSet.next) { NSString *homeData = [resultSet stringForColumn:@"data"]; // Convert a string to an object. NSData *data = [homeData dataUsingEncoding:NSUTF8StringEncoding]; NSArray *array = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:NULL]; // Add it to the array [homeDatas addObject:array]; } return homeDatas.copy; }Copy the code
4. Use FMDB(emphasis!!) Load the data in the database before requesting it
NSArray *array = [SQLiteManager queryHomeData]; InformationReturnData * InformationReturnData = [InformationReturnData mj_objectWithKeyValues:array.firstObject]; self.listDataArray = returnData.data; [self.tableView reloadData]; } else {/ / not heavy, loaded into the data in the database to the server requesting data [self requestDataWithPage: self. The page]. }Copy the code
5. Write data to database (must be after data request back!
NSError *err = nil; / / here is the object into a json string written to the database (database can not save object, you will know ~) NSData * data = [NSJSONSerialization dataWithJSONObject: jsonData options:NSJSONWritingPrettyPrinted error:&err]; NSString *jsonStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; NSInteger page = returnData.page; / / delete old data before [SQLiteManager deleteHomeDataWithPage: page]. // Save new data [SQLiteManager insertHomeData:jsonStr page:page];Copy the code