realm 的增刪改查

首先.導(dǎo)入Realm.framework,
把Realm.framework 拖到"Embedded Binaries"選項中。確認(rèn)Copy items if needed被選中后,點擊Finish按鈕;

<h4>一、創(chuàng)建數(shù)據(jù)庫</h4>

這步我是在 appdelegate didFinishLaunchingWithOptions中做的

事實上 并不用創(chuàng)建數(shù)據(jù)庫

//創(chuàng)建數(shù)據(jù)庫
- (void)creatDataBaseWithName:(NSString *)databaseName
{
    NSArray *docPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *path = [docPath objectAtIndex:0];
    NSString *filePath = [path stringByAppendingPathComponent:databaseName];
    NSLog(@"數(shù)據(jù)庫目錄 = %@",filePath);

    RLMRealmConfiguration *config = [RLMRealmConfiguration defaultConfiguration];
    config.fileURL = [NSURL URLWithString:filePath];
//    config.objectClasses = @[MyClass.class, MyOtherClass.class];
    config.readOnly = NO;
    int currentVersion = 1.0;
    config.schemaVersion = currentVersion;
    
//    config.migrationBlock = ^(RLMMigration *migration , uint64_t oldSchemaVersion) {
//        // 這里是設(shè)置數(shù)據(jù)遷移的block
//        if (oldSchemaVersion < currentVersion) {
//        }
//    };
    [RLMRealmConfiguration setDefaultConfiguration:config];
}

二、創(chuàng)建表

每一個繼承自RLMObject 的模型可以理解為一個表
.h文件中

#import <Realm/Realm.h>
@interface RLMPt : RLMObject
@property NSString *cName;
@property NSString *cLevel;
@end

.m文件中

#import "RLMPt.h"
@implementation RLMPt
//設(shè)置 主鍵
+ (NSString *)primaryKey {
    return @"cLevel";
}
//設(shè)置屬性默認(rèn)值
+ (NSDictionary *)defaultPropertyValues{
    return @{@"cname":@"測試" };
}


//設(shè)置忽略屬性,即不存到realm數(shù)據(jù)庫中
+ (NSArray<NSString *> *)ignoredProperties {
    return @[@"cLevel"];
}
//樓下兩個屬性還有些迷糊
//一般來說,屬性為nil的話realm會拋出異常,但是如果實現(xiàn)了這個方法的話,就只有name為nil會拋出異常,也就是說現(xiàn)在cover屬性可以為空了
+ (NSArray *)requiredProperties {
    return @[@"cLevel"];
}

//設(shè)置索引,可以加快檢索的速度
+ (NSArray *)indexedProperties {
    return @[@"ID"];
}
@end

三、增刪改查

增.改

        RLMRealm *realm = [RLMRealm defaultRealm];
        [realm  beginWriteTransaction];
        RLMPt *pt   =   [RLMPt new];
        pt.cName    =   self.name.text;
        pt.cLevel   =   self.level.text;
  //        [ realm addObject:pt];
        [realm addOrUpdateObject:pt];
    [RLMPt createOrUpdateInRealm:realm withValue:@{@"cName": @"9", @"cLevel": @"1"}];

//根據(jù)主鍵 決定是修改,還是增加
        [ realm commitWriteTransaction];

addOrUpdateObject會去先查找有沒有傳入的pt相同的主鍵,如果有,就更新該條數(shù)據(jù)。這里需要注意,addOrUpdateObject這個方法不是增量更新,所有的值都必須有,如果有哪幾個值是null,那么就會覆蓋原來已經(jīng)有的值,這樣就會出現(xiàn)數(shù)據(jù)丟失的問題。
createOrUpdateInRealm:withValue:這個方法是增量更新的,后面?zhèn)饕粋€字典,使用這個方法的前提是有主鍵。方法會先去主鍵里面找有沒有字典里面?zhèn)魅氲闹麈I的記錄,如果有,就只更新字典里面的子集。如果沒有,就新建一條記錄。

    RLMRealm *realm = [RLMRealm defaultRealm];
    [realm beginWriteTransaction];
    RLMResults<RLMPt *> *pt = [RLMPt allObjects];
    // 刪除單條記錄
        [realm deleteObject:pt[0]];
    // 刪除多條記錄
    //    [self.realm deleteObjects:@[pt1.pt2]];
    // 刪除所有記錄
    //    [realm deleteAllObjects];
    [realm commitWriteTransaction];

    
    RLMResults<RLMPt *> *pt = [RLMPt allObjects];
    //從默認(rèn)數(shù)據(jù)庫查詢所有
    // 使用斷言字符串查詢
    //    RLMResults<RLMPt *> *pt = [RLMPt objectsWhere:@"cLevel = '1'"];
     NSLog(@"%@",pt);

/* 另一個 demo 中的方法 沒有進(jìn)行驗證
    // 使用 NSPredicate 查詢
//    NSPredicate *pred = [NSPredicate predicateWithFormat:@"color = %@ AND name BEGINSWITH %@",
//                         @"棕黃色", @"大"];
//    RLMResults *results = [Dog objectsWithPredicate:pred];
//
//    // 排序名字以“大”開頭的棕黃色狗狗
//    RLMResults<Dog *> *sortedDogs = [[Dog objectsWhere:@"color = '棕黃色' AND name BEGINSWITH '大'"] sortedResultsUsingProperty:@"name" ascending:YES];
*/

注意:

1.模型需要繼承RLMObject
2.如果是INT 類型 應(yīng)使用NSNumber<RLMInt>
3.屬性類型需要對應(yīng)正確 string int 不可混淆

reason: '-[__NSCFNumber UTF8String]: unrecognized selector sent to instance 0xb000000000000473'

4.修改過屬性類型后,需要刪除項目,重新運行.

'Migration is required due to the following errors:
- Property 'HSAccount.personInfoId' has been changed from 'int' to 'string'.'

5.必須設(shè)置主鍵,否則無法更新數(shù)據(jù)

reason: ''HSAccount' does not have a primary key and can not be updated'

6.設(shè)置完主鍵后需要刪除項目,再次運行

reason: 'Migration is required due to the following errors:
- Primary Key for class 'HSAccount has been added.'
reason: 'Migration is required due to the following errors:
- Property 'HSAccount.personInfoId' has been made optional.'

7.主鍵必須是類的一個屬性

reason: 'Primary key property 'hahaha' does not exist on object 'HSAccount''

參考 : http://www.itdecent.cn/p/50e0efb66bdf

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容