@interface TbNote : NSObject { int index; NSString *title; NSString *body; } @property (nonatomic, retain) NSString *title; @property (nonatomic, retain) NSString *body; - (id)initWithIndex:(int)newIndex Title:(NSString *)newTitle Body:(NSString *)newBody; - (int)getIndex; @end //TbNote.m #import "TbNote.h" @implementation TbNote @synthesize title, body; - (id)initWithIndex:(int)newIndex Title:(NSString *)newTitle Body:(NSString *)newBody{ if(self = [super init]){ index = newIndex; self.title = newTitle; self.body = newBody; } return self; } - (int)getIndex{ return index; } - (void)dealloc { [title release]; [body release]; [super dealloc]; } @end 创建DAO(Data Access Objects) 这里将FMDB 的函数调用封装为DAO 的方式。 //BaseDao.h #import <Foundation/Foundation.h> @class FMDatabase; @interface BaseDao : NSObject { FMDatabase *db; } @property (nonatomic, retain) FMDatabase *db; -(NSString *)setTable:(NSString *)sql; @end //BaseDao.m #import "SqlSampleAppDelegate.h" #import "FMDatabase.h" #import "FMDatabaseAdditions.h" #import "BaseDao.h" @implementation BaseDao @synthesize db; - (id)init{ if(self = [super init]){ // 由AppDelegate 取得打开的数据库 SqlSampleAppDelegate *appDelegate = (SqlSampleAppDelegate *)[[UIApplication sharedApplication] delegate]; db = [[appDelegate db] retain]; } return self; } // 子类中实现 -(NSString *)setTable:(NSString *)sql{ return NULL; } - (void)dealloc { [db release]; [super dealloc]; } @end 下面是访问TbNote 表格的类。 //TbNoteDao.h #import <Foundation/Foundation.h> #import "BaseDao.h" @interface TbNoteDao : BaseDao { } -(NSMutableArray *)select; -(void)insertWithTitle:(NSString *)title Body:(NSString *)body; -(BOOL)updateAt:(int)index Title:(NSString *)title Body:(NSString *)body; -(BOOL)deleteAt:(int)index; @end //TbNoteDao.m #import "FMDatabase.h" #import "FMDatabaseAdditions.h" #import "TbNoteDao.h" #import "TbNote.h" @implementation TbNoteDao -(NSString *)setTable:(NSString *)sql{ return [NSString stringWithFormat:sql, @"TbNote"]; } // SELECT -(NSMutableArray *)select{ NSMutableArray *result = [[[NSMutableArray alloc] initWithCapacity:0] autorelease]; FMResultSet *rs = [db executeQuery:[self setTable:@"SELECT * FROM %@"]]; while ([rs next]) { TbNote *tr = [[TbNote alloc] initWithIndex:[rs intForColumn:@"id"] Title:[rs stringForColumn:@"title"] Body:[rs stringForColumn:@"body"] ]; [result addObject:tr]; [tr release]; } [rs close]; return result; } // INSERT -(void)insertWithTitle:(NSString *)title Body:(NSString *)body{ [db executeUpdate:[self setTable:@"INSERT INTO %@ (title, body) VALUES (?,?)"], title, body]; if ([db hadError]) { NSLog(@"Err %d: %@", [db lastErrorCode], [db lastErrorMessage]); } } // UPDATE -(BOOL)updateAt:(int)index Title:(NSString *)title Body:(NSString *)body{ BOOL success = YES; [db executeUpdate:[self setTable:@"UPDATE %@ SET title=?, body=? WHERE id=?"], title, body, [NSNumber numberWithInt:index]]; if ([db hadError]) { NSLog(@"Err %d: %@", [db lastErrorCode], [db lastErrorMessage]); |