除了FMDB,Realm也是一種很流行的數據庫方案。
1. 官方資料
- (最新版)Realm Objective?C官方文檔地址 https://realm.io/docs/objc/latest/
- (中文版)Realm Objective?C官方文檔地址(內容相對英文版不一定是最新的)https://realm.io/cn/docs/objc/latest/
- Realm官方API查閱手冊 https://realm.io/docs/objc/latest/api/
- GitHub源碼地址 https://github.com/realm/realm-cocoa
- 也可以直接點擊壓縮包下載
2. 用法示例
2.1 新建數據模型
Student.h
#import <Realm/Realm.h>
#import <UIKit/UIKit.h>
@interface Student : RLMObject
@property int age;
@property NSString *name;
@property (nonatomic,strong) NSData *showImgData;
@end
// This protocol enables typed collections. i.e.:
// RLMArray<Student>
RLM_ARRAY_TYPE(Student)
2.2 調用前初始化數據庫
- (BOOL)initRealm {
self.isFisrtUser= YES;
[self setDefaultRealmForUser:[CommonUtils getStrValueInUDWithKey:@"account"]];
self.userNameLbl.text = @"user1";
config.fileURL = [[[config.fileURL URLByDeletingLastPathComponent]
URLByAppendingPathComponent:@"user1"]
URLByAppendingPathExtension:@"realm"];
NSLog(@"Realm file path: %@", config.fileURL);
NSError *error;
_realm = [RLMRealm realmWithConfiguration:config error:&error];
if (nil != error) {
NSLog(@"Create Realm Error");
return NO;
}
NSLog(@"create realm success");
return YES;
}
2.3 增數據
//增
- (IBAction)onAdd:(id)sender {
if (_nameTF.text.length ==0 || _ageTF.text.length == 0) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Empty"
message:@"Name or Age is empty!"
delegate:self
cancelButtonTitle:@"Return"
otherButtonTitles:nil];
[alert show];
return ;
}
Student *s= [Student new];
s.name = _nameTF.text;
s.age = [_ageTF.text intValue];
s.showImgData = UIImagePNGRepresentation(self.showImgeView.image);
[_realm beginWriteTransaction];
[_realm addObject:s];
[_realm commitWriteTransaction];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Sucess"
message:@"Add Sucess!"
delegate:self
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alert show];
_allStudents = [Student allObjectsInRealm:_realm];
[_dataTV reloadData];
}
2.4 刪數據
//刪
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
Student *s = [_allStudents objectAtIndex:indexPath.row];
if (s == nil) {
NSLog(@"s is nil");
return;
}
[_realm beginWriteTransaction];
[_realm deleteObject:s];
[_realm commitWriteTransaction];
[tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
}
2.5 改數據
- (IBAction)onModify:(id)sender {
if (_nameTF.text.length ==0 || _ageTF.text.length == 0) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Empty"
message:@"Name or Age is empty!"
delegate:self
cancelButtonTitle:@"Return"
otherButtonTitles:nil];
[alert show];
return ;
}
[_realm beginWriteTransaction];
_student.name = _nameTF.text;
_student.age = _ageTF.text.intValue;
[_realm commitWriteTransaction];
UINavigationController *vc = (UINavigationController *)self.parentViewController;
[vc popViewControllerAnimated:YES];
}
2.6 查數據
//查
- (IBAction)onQuery:(id)sender {
if (_filterTF.text.length == 0) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Empty"
message:@"Filter Age is empty!"
delegate:self
cancelButtonTitle:@"Return"
otherButtonTitles:nil];
[alert show];
return ;
}
NSString *filter = [NSString stringWithFormat:@"age > %d", [_filterTF.text intValue ]];
if (_realm) {
_allStudents = [Student objectsInRealm:_realm where:filter];
}
[_dataTV reloadData];
}
2.7 切換用戶
很多App有這樣一個需求:第一個賬號保存第一個數據庫,切換到第二個賬號時,再新建第二個數據庫,并且無法查看第一個用戶的數據,當用戶切換回第一個賬號時,能繼續使用第一個數據庫。
- (void)setDefaultRealmForUser:(NSString *)username {
RLMRealmConfiguration *config = [RLMRealmConfiguration defaultConfiguration];
// 使用默認的目錄,但是使用用戶名來替換默認的文件名
config.fileURL = [[[config.fileURL URLByDeletingLastPathComponent]
URLByAppendingPathComponent:username]
URLByAppendingPathExtension:@"realm"];
// 將這個配置應用到默認的 Realm 數據庫當中
[RLMRealmConfiguration setDefaultConfiguration:config];
}