MojoDatabase 是一个用于 iOS 应用的 Objective-C 编写的 ActiveRecord 风格的 ORM,适用于 SQLite。
目标是通过 ActiveRecord 模式为使用 Objective-C 应用的 SQLite 提供更友好的用户界面。
要安装 Mojo 数据库,只需将 MojoDatabase 目录拖放到您的 XCode 项目中,并在提示时选择“将文件复制到目标位置”。
Mojo 数据库与您的 Objective-C 应用程序有两种(2)种交互方式。
在 easyios 中分离出来,移除了 jsonmodel,单独使用
在您的应用程序代理头文件中,您应该创建一个实例变量,用于在应用程序中引用数据库。
@class MojoDatabase;
@interface MyAppDelegate : NSObject <UIApplicationDelegate> {
MojoDatabase *myDatabase;
}
@property (nonatomic, retain) MojoDatabase *myDatabase;
@end
在您的应用程序代理实现文件中,您应包含 AppDatabase.h 头文件,并在应用程序启动过程中建立到您的数据库的连接。
#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
这将初始化(如果尚不存在,则创建数据库)并更新数据库到当前版本,通过运行任何缺失的迁移。
如果需要,您可以通过更改顶部的 code骁的 kDatabaseName
字符串来自定义由 AppDatabase.m 文件创建的 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
稍后从数据库中检索该朋友对象
NSArray *records = [self findByColumn:@"name" value:@"Norman Rockwell"];
if ( [records count] ) {
Friend *normanRockwell = [records objectAtIndex:0];
}
请注意,code骁 的 findByColumn
总是返回一个 NSArray
对象。
请使用GitHub Issues 跟踪器来提交任何bug报告或功能请求。
如果您想为Mojo Database做出贡献,请fork该项目并发送pull请求。
Mojo Database主要基于Dylan Bruzenak在Apress出版的《iPhone Advanced Projects》一书中的代码,并由Craig P Jolicoeur修改和扩展。