因为自己以前接触过SQL Server,基于SQL命令的相同,所以就选择SQLite做本地存储,而没有用coreData、XML/plist、或其他什么?
先要导入Framework库:libsqlite3.0.dylib, 头文件调用#import <sqlite3.h>,再定义个全局变量sqlite3 *database 作为数据库对象。准备工作完成!
核心代码如下,了解Sql的人同能理解什么意思。
1 -(void) QueryTable;
2 {
3 // Setup the database object
4 sqlite3 *database;
5 catalogMenus = [[NSMutableArray alloc] init];
6 // Open the database from the users filessytem
7 if(sqlite3_open([[appDelegate getDBPath:dbName] UTF8String], &database) == SQLITE_OK)
01 // Setup the SQL Statement and compile it for faster access
02 const char *sqlStatement = “select * from table_catalogs”;
03 sqlite3_stmt *compiledStatement;
04 if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) // Loop through the results and add them to the feeds array
05 while(sqlite3_step(compiledStatement) == SQLITE_ROW) {
06 // Read the data from the result row
07 NSMutableString *ID = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 0)];
08 NSMutableString *name = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 1)];
09 NSMutableString *pic = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 2)];
10
view source
print?
01 // add catalog to menus
02 Category *catalog = [Category catalogsWithUID:ID name:name thumb:pic];
03 [catalogMenus addObject:catalog];
04 }
05 }
06 // Release the compiled statement from memory
07 sqlite3_finalize(compiledStatement);
08 }
09 // Important To Print Out Values for Objects
10 for (Category *itm in catalogMenus)
11 {
12 NSLog(@”id:%@, name:%@”,itm.categoryID, itm.categoryName);
13 }
14 NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@”id” ascending:YES];
15 NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
16 NSArray *sortedArray = [catalogMenus sortedArrayUsingDescriptors:sortDescriptors];
17 catalogMenus = [sortedArray mutableCopy];
18
19 sqlite3_close(database);
20 }