iPhone开发进阶(9)— 用SQLite管理数据库 (转载)
iPhone开发进阶(9)— 用SQLite管理数据库
?
?接下来再看看用 DAO 的形式来访问数据库的使用方法,代码整体构造如下。
?
?首先创建如下格式的数据库文件:
?最后我们开看看连接DB,和添加 ViewController 的处理。这一同样不使用 Interface Builder。
//SqlSampleAppDelegate.h#import <UIKit/UIKit.h>@class FMDatabase;@interface SqlSampleAppDelegate : NSObject <UIApplicationDelegate> { UIWindow *window; FMDatabase *db;}@property (nonatomic, retain) IBOutlet UIWindow *window;@property (nonatomic, retain) FMDatabase *db;- (BOOL)initDatabase;- (void)closeDatabase;@end//SqlSampleAppDelegate.m#import "SqlSampleAppDelegate.h"#import "FMDatabase.h"#import "FMDatabaseAdditions.h"#import "NoteController.h"@implementation SqlSampleAppDelegate@synthesize window;@synthesize db;- (void)applicationDidFinishLaunching:(UIApplication *)application { if (![self initDatabase]){ NSLog(@"Failed to init Database."); } NoteController *ctrl = [[NoteController alloc] initWithNibName:nil bundle:nil]; [window addSubview:ctrl.view]; [window makeKeyAndVisible];}- (BOOL)initDatabase{ BOOL success; NSError *error; NSFileManager *fm = [NSFileManager defaultManager]; NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:@"sample.db"]; success = [fm fileExistsAtPath:writableDBPath]; if(!success){ NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"sample.db"]; success = [fm copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error]; if(!success){ NSLog([error localizedDescription]); } success = NO; } if(success){ db = [[FMDatabase databaseWithPath:writableDBPath] retain]; if ([db open]) { [db setShouldCacheStatements:YES]; }else{ NSLog(@"Failed to open database."); success = NO; } } return success;}- (void) closeDatabase{ [db close];}- (void)dealloc { [db release]; [window release]; [super dealloc];}@end??
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?