MojoDatabase是一个使用Objective-C编写的类似ActiveRecord的ORM,用于iOS应用程序。
目标是提供更好的用户界面,以ActiveRecord模式通过SQLite在Objective-C应用程序中使用SQLite。
要安装Mojo Database,只需将MojoDatabase目录拖入您的XCode项目,并在提示时选择“将文件复制到目标位置”。
Mojo Database与Objective-C应用程序有两种(2)类型的交互。
在您的应用程序代理头文件中,应该创建一个实例变量,在应用程序中将用来引用数据库。
@class MojoDatabase;
@interface MyAppDelegate : NSObject <UIApplicationDelegate> {
MojoDatabase *myDatabase;
}
@property (nonatomic, retain) MojoDatabase *myDatabase;
@end
在您的应用程序代理实现文件中,您应该包含AppDatabase.h头文件并在应用程序启动过程中创建与DB的连接。
#import "AppDatabase.h"
@implementation MyAppDelegate
-(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Setup Connection to the database
self.database = [[[AppDatabase alloc] initWithMigrations] autorelease];
}
-(void)dealloc {
[database release], database=nil;
[super dealloc];
}
@end
这将初始化(并在不存在的情况下创建您的数据库)并更新数据库到当前版本,通过运行任何缺失的迁移。
如果需要,您可以通过更改AppDatabase.m
文件顶部的kDatabaseName
字符串来自定义由其创建的SQLite数据库的名称。
您创建的每个模型都应该直接映射到通过迁移条目创建的SQLite表。所以,如果您的AppDatabase.m
中有以下迁移方法
-(void)createFriendTable {
[self executeSql:@"CREATE TABLE Friend (primaryKey INTEGER primary key autoincrement, name TEXT, age INTEGER)"];
}
您将还有一个名为Friend
的Objective-C类,该类从MojoModel
派生。以下是一个示例 Friend.h
头文件
#import "MojoModel.h"
@interface Friend : MojoMdel {
}
@property (nonatomic, retain) NSString *name;
@property (nonatomic, retain) NSNumber *age;
@end
和以下基本Friend.m
实现文件
#import "Friend.h"
@implementation Friend
@synthesize name=_name;
@synthesize age=_age;
-(void)dealloc {
[_name release], _name=nil;
[_age release], _age=nil;
[super dealloc];
}
@end
创建一个新的朋友对象并将其保存到数据库中会像这样简单
Friend *newFriend = [[Friend alloc] init];
newFriend.name = @"Norman Rockwell";
newFriend.age = [NSNumber numerWithInteger:55];
[newFriend save]; // this will write out the new friend record to the databse
以后要检索数据库中的那个Friend对象
NSArray *records = [self findByColumn:@"name" value:@"Norman Rockwell"];
if ( [records count] ) {
Friend *normanRockwell = [records objectAtIndex:0];
}
请注意,findByColumn
总是返回一个NSArray
对象。
请使用GitHub Issues追踪器进行任何错误报告或功能请求。
如果您希望为 Mojo 数据库做贡献,请分支项目并提交 pull 请求。
Mojo 数据库主要基于 Apress 出版的《iPhone 高级项目》一书中的 Dylan Bruzenak 的代码,并由 Craig P Jolicoeur 进行了修改和扩展。