精华内容
参与话题
问答
  • Realm

    2019-07-23 10:25:24
    1、环境配置 2、原理 3、比较 【参考】 1、Realm数据库 从入门到“放弃”

    一、环境配置

    1.1 安装Realm

    • GitHub下载
    • CocoaPods

    1.2 Xcode插件

    下载完打开plugin/RealmPlugin.xcodeproj并运行,重启Xcode,新建一个RLMObject类,如下:

    RLMObject

    1.3 Realm Browser(可视化工具 )

    App Store中下载安装 Realm Browser,帮助更好查看数据的增删改查

    二、实践&原理

    2.1 模型属性

    Post

    Post.h
    #import <Realm/Realm.h>
    @class User; // 避免交叉引用
    
    RLM_ARRAY_TYPE(Post)
    
    @interface Post : RLMObject
    
    @property User *user; // 对一
    
    @property NSString *postID;
    @property NSString *title;
    @property NSDate *timestamp;
    @property NSData *content;
    @property NSInteger look; // defaultPropertyValues
    @property NSNumber<RLMBool> *isTop; // 常量在Realm数据库里边是不可以为空,所以存储为NSNumber
    @property RLMArray <Post *><Post> *comments; // 对多
    
    // 不支持CGFloat,请使用float和double
    
    @end
    
    Post.m
    #import "Post.h"
    
    @implementation Post
    
    // 可空属性,决定属性是否可以为nil
    + (NSArray<NSString *> *)requiredProperties {
        return @[@"title"];
    }
    
    + (NSDictionary *)defaultPropertyValues {
        return @{
                 @"look": @(0)
                 };
    }
    
    // 忽略属性
    + (NSArray *)ignoredProperties {
        return @[];
    }
    
    // 索引属性,支持NSString,NSNumber(包括常量),NSDate
    + (NSArray<NSString *> *)indexedProperties {
        return @[@"title", @"timestamp"];
    }
    
    // 主键(唯一性)
    + (NSString *)primaryKey {
        return @"postID";
    }
    

    User

    User.h
    #import <Realm/Realm.h>
    
    @interface User : RLMObject
    
    @property NSString *nickName;
    @property NSString *hobby;
    @property (readonly) RLMLinkingObjects *posts; // 对多(RLMLinkingObjects继承自RLMResults)
    
    @end
    
    // This protocol enables typed collections. i.e.:
    // RLMArray<User *><User>
    RLM_ARRAY_TYPE(User)
    
    User.m
    + (NSDictionary<NSString *,RLMPropertyDescriptor *> *)linkingObjectsProperties {
        return @{
                 @"posts": [RLMPropertyDescriptor descriptorWithClass:Post.class propertyName:@"user"]
                 };
    }
    

    Test

    Post *post = [[Post alloc] initWithValue:@{@"postID": @"5201314", @"title": @"undefined"}];
    User *user = [[User alloc] init];
    user.hobby = @"tennis";
    post.user = user;
    
    RLMRealm *realm = [RLMRealm defaultRealm];
    [realm transactionWithBlock:^{
        [realm addObject:post];
        [realm addObject:user];
        
        NSLog(@"%@", user.posts);
    }];
    

    2.2 数据库操作

    [realm transactionWithBlock:^{
        [realm addObject:post]; // 增
    }];
    

    [realm transactionWithBlock:^{
        [realm deleteObject:post];
        [realm deleteAllObjects]; // 删
    }];
    

    针对某个对象修改&实时性
    [realm transactionWithBlock:^{
        post.timestamp = [NSDate date]; // 改
    }];
    
    通过主键更新
    Post *postReset = [[Post alloc] init];
    postReset.postID = @"52011314";
    postReset.title = @"真香";
    postReset.timestamp = [NSDate date];
    [realm transactionWithBlock:^{
       [realm addOrUpdateObject:postReset];
    }];
    
    批量修改(支持KVC)
    RLMResults *results = [Post allObjects];
    [realm transactionWithBlock:^{
        [results setValue:[NSDate date] forKey:@"timestamp"];
    }];
    

    等于
    RLMResults *results = [Post objectsWhere:@"title == %@", @"undefined"];
    
    Post *postBeFound = [results firstObject];
    
    [realm transactionWithBlock:^{
        post.title = @"hihihi";
    }];
    
    NSLog(@"%@", postBeFound);
    
    大于小于
    // AND
    RLMResults *results = [Post objectsWhere:@"look < 20 AND look > 0"];
    
    // BETWEEN
    RLMResults *results = [Post objectsWhere:@"look BETWEEN {10, 80}"];
    
    包含
    // [c]不区分大小写
     RLMResults *results = [Post objectsWhere:@"title CONTAINS[c] 'hi'"];
    
    链式检索
    RLMResults *results = [Post objectsWhere:@"comments.@count > 0"];
    RLMResults *finalResults = [results objectsWhere:@"look > 10"];
    NSLog(@"%@", finalResults);
    
    排序
    // 不影响数据库中的排序
    RLMResults *results = [Post allObjects];
    RLMResults *sortResult = [results sortedResultsUsingKeyPath:@"look" ascending:YES];
    NSLog(@"%@", sortResult);
    
    分页

    没有分页功能,通过惰性加载

    2.3 数据库基本配置

    查看路径及相关配置:

    RLMRealmConfiguration *defaultRealm = [RLMRealmConfiguration defaultConfiguration];
    NSLog(@"%@", defaultRealm);
    

    打印:

    打印结果

    其中几个参数:

    参数 意义
    inMemoryIdentifier
    encryptionKey
    readOnly
    schemaVersion
    deleteRealmIfMigrationNeeded
    shouldCompactOnLaunch
    dynamic
    customSchema
    RLMRealmConfiguration *defaultRealm = [RLMRealmConfiguration defaultConfiguration];
    defaultRealm.fileURL = [[NSBundle mainBundle] URLForResource:@"default" withExtension:@"realm"];
    defaultRealm.readOnly = YES;
    RLMRealm *realm = [RLMRealm realmWithConfiguration:defaultRealm error:nil];
    
    // 内存数据库
    RLMRealmConfiguration *memoryRealm = [RLMRealmConfiguration defaultConfiguration];
    memoryRealm.inMemoryIdentifier = @"memoryDB";
    RLMRealm *realmMem = [RLMRealm realmWithConfiguration:memoryRealm error:nil];
    
    
    // 数据库写入通知
    

    2.4 数据库版本迁移

    RLMRealmConfiguration *realmConf = [RLMRealmConfiguration defaultConfiguration];
    uint64_t currentVersion = 3;
    realmConf.schemaVersion = currentVersion;
    [realmConf setMigrationBlock:^(RLMMigration * _Nonnull migration, uint64_t oldSchemaVersion) {
       if(oldSchemaVersion < currentVersion) {
           [migration enumerateObjects:NSStringFromClass([Post class]) block:^(RLMObject * _Nullable oldObject, RLMObject * _Nullable newObject) {
               newObject[@"hot"] = @([oldObject[@"look"] integerValue]);
           }];
    
           // 属性重命名
           [migration renamePropertyForClass:NSStringFromClass([Post class]) oldName:@"title" newName:@"postTitle"];
       }
    }];
    RLMRealm *realm = [RLMRealm realmWithConfiguration:realmConf error:nil];
    

    在这里插入图片描述
    在这里插入图片描述
    常量在RLM数据库中不能为空

    三、比较

    RLMObject 与 NSManagerObject

    不可重写setter和getter
    RLMObject:支持ignore属性;NSManagerObject需要@dynamic属性

    【参考】

    1、官方文档

    2、Realm数据库 从入门到“放弃”

    3、手把手教你从Core Data迁移到Realm

    4、iOS Realm简单使用(增删改查和排序)

    展开全文
  • realm

    2018-11-18 16:07:56
    realm的使用 1.依赖的使用: classpath "io.realm:realm-gradle-plugin:2.2.1" //项目下导入的依赖 //bulid下导入的 apply plugin: 'realm-android'  2.工具类的编写 public class ReamlUtils { ...

    realm的使用

    1.依赖的使用:

    classpath "io.realm:realm-gradle-plugin:2.2.1" //项目下导入的依赖
    //bulid下导入的
    apply plugin: 'realm-android'

     2.工具类的编写

    public class ReamlUtils   {
    
        private static ReamlUtils reamlUtils;
    
        private ReamlUtils(){ }
    
        public static ReamlUtils getReamlInstens(){
            if (reamlUtils == null){
                synchronized (ReamlUtils.class){
                    reamlUtils = new ReamlUtils();
                }
            }
            return reamlUtils;
        }
    
        public void initRealm(Context context) {
            Realm.init(context);
        }
    
        /**
         * 创建数据库
         * */
        private static Realm mRealm=null;
    
        public  RealmBuilder getRealm() {
            if (mRealm == null) {
                RealmConfiguration config = new RealmConfiguration.Builder()
                        .name("myrealm.realm") //文件名
                        .schemaVersion(0) //版本号
                        .deleteRealmIfMigrationNeeded()//版本冲突时自动删除原有的版本
                        .build();
                mRealm = Realm.getInstance(config);
            }
            return new RealmBuilder(mRealm);
        }
    
        public static class RealmBuilder{
            private Realm realm;
    
            public RealmBuilder(Realm realm){
                this.realm = realm;
            }
    
            /**
             * 关闭数据库
             */
    
            public void closeReml() {
                realm.close();
            }
    
            /**
             * 更改第一个
             * */
            public <D extends RealmModel> void changeFirst(final D d,final OnChangeRelmListener listener){
                mRealm.executeTransaction(new Realm.Transaction() {
                    @Override
                    public void execute(Realm r) {
                        //先查找后得到User对象
                        D bean = (D) mRealm.where(d.getClass()).findFirst();
                        listener.change(bean);
                    }
                });
            }
            /**
             * 更改数据库数据 change
             * */
            public <D extends RealmModel> void changeRealm(final D d,final OnChangeRelmListener listener){
                mRealm.executeTransaction(new Realm.Transaction() {
                    @Override
                    public void execute(Realm r) {
                        try {
                            RealmResults<D> list = (RealmResults<D>) mRealm.where(d.getClass()).findAll();
                            listener.change(list.get(list.size()-1));
                        }catch (Exception e){
                            e.printStackTrace();
                        }
                    }
                });
            }
    
            /**
             * 数据库增加数据,没有主键@PrimaryKey  add
             * */
            public <D extends RealmModel> void addRealm(final D d){
                mRealm.executeTransaction(new Realm.Transaction() {
                    @Override
                    public void execute(Realm r) {
                        mRealm.copyToRealm(d);
                    }
                });
            }
            /**
             * 数据库增加数据,有主键@PrimaryKey  add
             * */
            public <D extends RealmModel> void addRealmKey(final D d){
                mRealm.executeTransaction(new Realm.Transaction() {
                    @Override
                    public void execute(Realm r) {
                        mRealm.copyToRealmOrUpdate(d);
                    }
                });
            }
    
            /**
             * 数据库增加数据,通过回调方式  add
             * */
            public <D extends RealmModel> void add(D d,OnChangeRelmListener listener){
                mRealm.beginTransaction();//开启事务
                D bean = (D) mRealm.createObject(d.getClass());
                listener.change(bean);
                mRealm.commitTransaction();//提交事务
            }
    
            /**
             * 在UI和后台线程同时开启创建write的事务,可能会导致ANR错误。为了避免该问题,可以使用executeTransactionAsync来实现
             * */
            public <D extends RealmModel> void addAsync(final D d,final OnChangeRelmListener listener){
                RealmAsyncTask transaction = mRealm.executeTransactionAsync(new Realm.Transaction() {
                    @Override
                    public void execute(Realm realm) {
                        D bean = (D) realm.createObject(d.getClass());
                        listener.change(bean);
                    }
                });
            }
    
            /**
             * 添加数据,设置监听回调,检测是否添加成功
             * */
    
            private RealmAsyncTask transaction;
            public <D extends RealmModel> void addAsyncState(final D d,final OnChangeRelmListener listener){
                transaction =  mRealm.executeTransactionAsync(new Realm.Transaction() {
                    @Override
                    public void execute(Realm realm) {
    
                    }
                }, new Realm.Transaction.OnSuccess() {
                    @Override
                    public void onSuccess() {
                        //成功回调
                        D bean = (D) mRealm.createObject(d.getClass());
                        listener.change(bean);
                    }
                }, new Realm.Transaction.OnError() {
                    @Override
                    public void onError(Throwable error) {
                        //失败回调
                    }
                });
            }
            /**
             * 如果当Acitivity或Fragment被销毁时,在OnSuccess或OnError中执行UI操作,将导致程序奔溃 。用RealmAsyncTask .cancel();可以取消事务 在onStop中调用,避免crash
             * */
            public void onStopAsync () {
                if (transaction != null && !transaction.isCancelled()) {
                    transaction.cancel();
                }
            }
    
            /**
             * 使用Json字符串插入数据 没有主键
             * */
            public <D extends RealmModel> void addJson(final D d,final String json,final OnChangeRelmListener listener){
                mRealm.executeTransaction(new Realm.Transaction() {
                    @Override
                    public void execute(Realm realm) {
                        mRealm.createObjectFromJson(d.getClass(), json);
                    }
                });
            }
            /**
             * 使用Json字符串插入数据  有主键
             * */
            public <D extends RealmModel> void addJsonKey(final D d,final String json,final OnChangeRelmListener listener){
                mRealm.executeTransaction(new Realm.Transaction() {
                    @Override
                    public void execute(Realm realm) {
                        mRealm.createOrUpdateObjectFromJson(d.getClass(), json);
                    }
                });
            }
    
            /**
             * 查找第一条数据
             * */
            public <D extends RealmModel> D findFirst(D d){
                D bean = (D) mRealm.where(d.getClass()).findFirst();
                return bean;
            }
            /**
             *根据条件进行获取
             * name为value的所有数据
             * */
            public <D extends RealmModel> D findRealmSelected(D d,String name,String value){
                RealmResults<D> userList = (RealmResults<D>)mRealm.where(d.getClass())
                        .equalTo(name, value).findAll();
                return userList.first();
            }
            /**
             * 查找最后一条数据
             * */
            public <D extends RealmModel> D findLast(final D d){
                RealmResults<D> userList = (RealmResults<D>) mRealm.where(d.getClass()).findAll();
                return userList.get(userList.size()-1);
            }
    
            /**
             * 查找数据
             * */
            public <D extends RealmModel> RealmResults<D> findAll(final D d){
                RealmResults<D> userList = (RealmResults<D>) mRealm.where(d.getClass()).findAll();
                return userList;
            }
            /**
             * 查找排序
             * */
            public <D extends RealmModel> void findAllSort(final D d){
                RealmResults<D> userList = (RealmResults<D>) mRealm.where(d.getClass()).findAll();
                RealmResults<D> result = userList.sort("age"); //根据age,正序排列
                result = userList.sort("age", Sort.DESCENDING);//逆序排列
            }
    
            /**
             * 根据name 获取value
             * */
            public <D extends RealmModel> D findAll(final D d,String name){
                RealmResults<D> userList = (RealmResults<D>)mRealm.where(d.getClass())
                        .isEmpty(name).findAll();
                return userList.get(userList.size()-1);
            }
    
    
            /**
             * 删除完
             * */
            public <D extends RealmModel> void delAll(final D d){
                mRealm.executeTransaction(new Realm.Transaction() {
                    @Override
                    public void execute(Realm r) {
                        mRealm.delete(d.getClass());
                    }
                });
            }
    
            public <D extends RealmModel> void delRealm(final D d){
                mRealm.executeTransaction(new Realm.Transaction() {
                    @Override
                    public void execute(Realm r) {
                        RealmResults<D> userList = (RealmResults<D>) mRealm.where(d.getClass()).findAll();
                        userList.deleteAllFromRealm();
                    }
                });
            }
    
            /**
             * 删除某一个
             * */
            public <D extends RealmModel> void delRealmPosition(final D d,final int position){
                mRealm.executeTransaction(new Realm.Transaction() {
                    @Override
                    public void execute(Realm r) {
                        RealmResults<D> userList = (RealmResults<D>) mRealm.where(d.getClass()).findAll();
                        userList.deleteFromRealm(position);
                    }
                });
            }
    
            /**
             * 升级数据库
             * */
            public void updateRealm(int version){
                RealmConfiguration config = new RealmConfiguration.Builder()
                        .name("myrealm.realm") //文件名
                        .schemaVersion(version)
                        .migration(new CustomMigration())//升级数据库
                        .build();
            }
    
            public static  class CustomMigration implements RealmMigration {
                @Override
                public void migrate(DynamicRealm realm, long oldVersion, long newVersion) {
                    RealmSchema schema = realm.getSchema();
                    if (oldVersion == 0 && newVersion == 1) {
                        RealmObjectSchema personSchema = schema.get("User");
                        //新增@Required的id
                        personSchema
                                .addField("id", String.class, FieldAttribute.REQUIRED)
                                .transform(new RealmObjectSchema.Function() {
                                    @Override
                                    public void apply(DynamicRealmObject obj) {
                                        obj.set("id", "1");//为id设置值
                                    }
                                })
                                .removeField("age");//移除age属性
                        oldVersion++;
                    }
                }
            }
    
            public interface OnChangeRelmListener<D extends RealmModel> {
                void change(D d);
            }
        }
    
    }
    

     3.如何去使用,第一步在application中实例化

    public class App extends Application{
    
        @Override
        public void onCreate() {
            super.onCreate();
            ReamlUtils.getReamlInstens().initRealm(this);
        }
    }

     4.Bean的编写

    public class Bean extends RealmObject {
        @PrimaryKey
        private int id;
    
        private String content;
    
        public int getId() {
            return id;
        }
    
        public void setId(int id) {
            this.id = id;
        }
    
        public String getContent() {
            return content;
        }
    
        public void setContent(String content) {
            this.content = content;
        }
    }

    5、realm没有自动增长的主键,我暂时没有找到方法,我使用的是自己定义一个游标进行设置主键,那么如何去使用呢?

    @Override
        public void onClick(View v) {
            switch (v.getId()){
                case R.id.btn_query://查询数据
                    RealmResults<Bean> all = ReamlUtils.getReamlInstens().getRealm().findAll(new Bean());
                    for (int i = 0 ; i <all.size(); i ++){
                        Log.d("Tag",all.get(i).getContent()+"---");
                    }
                    Log.d("Tag",all.size()+"个");
                    break;
                case R.id.btn_ok://添加数据
                    String trim = edInput.getText().toString().trim();
                    Bean bean = new Bean();
                    bean.setId(i++);
                    bean.setContent(trim);
                    ReamlUtils.getReamlInstens().getRealm().addRealmKey(bean);
                    break;
            }
        }

     

    展开全文
  • t seem to be returning the correct value in this case, <code>Realm</code> functionality seems to be otherwise working correctly: <pre><code> System.out.println(c.eval(Source.create("js", "...
  • <div><p>I'm having a problem where I can't access some users in Realm Browser because it is out of update, some User IDs are already deleted, only Website ...realm/realm-object-server</p></div>
  • Realm is a mobile database that runs directly inside phones, tablets or wearables. This repository holds the source code for the iOS, macOS, tvOS & watchOS versions of Realm Swift & Realm ...
  • <div><p>Reported from realm-java https://github.com/realm/realm-java/issues/4023</p> <p>backtrace: <pre><code> ********** Crash dump: ********** Build fingerprint: 'google/bullhead/bullhead:6.0.1/...
  • t debug realm using stetho-realm Web SQL - Empty <p><img alt="capture" src="https://cloud.githubusercontent.com/assets/9895294/15455108/70ee15c8-2074-11e6-9665-dae0bef8dfe4.PNG" /></p> <p><strong>My ...
  • <p>Host with no realm gets a realm added --> Realm entry is created </li><li> <p>Host with a realm gets the realm removed --> Realm entry is removed 🌴 </li><li> <p>Host with a realm ...
  • ProcCmdline: /usr/lib/realm-object-server-developer/node/bin/node /usr/bin/realm-object-server -c /etc/realm/configuration.yml ProcCwd: /var/lib/realm/object-server/tmp ProcEnviron: LANG=en_US....
  • 2017-10-22T16:38:36.870Z - info: sync-client: Opening Realm file: /Users/janschwarz1/Downloads/realm-mobile-platform/realm-object-server/object-server/realm-object-server/listener/__admin.realm ...
  • <h2>Goals <p>View Realm and User information in Realm Studio - connected to ROS via HTTPS</p> <h2>Expected Results <p>Clicking on the Realm or User tab would ...realm/realm-object-server</p></div>
  • <code>required_realm</code> is never checked and the realm check could be bypassed entirely by simply not specifying a realm header! <p>One could even argue that the header isn't necessary as the...
  • however, it seems that rlm_krb5 always uses whatever is the default local kerberos realm for the RADIUS server - if the server is radius.example1.com it uses the EXAMPLE1.COM kerberos realm ...
  • Get realm of object

    2020-12-01 20:41:12
    t know which realm the object is located I can't use <code>realm?.object(ofType: CompanyModel.self, forPrimaryKey: id)</code> directly. I have to find which realm the object is located in first. I...
  • .realm file checksum

    2020-11-22 05:52:44
    <p>It adds a simple checksum to .realm files (sum of first and last 128 bytes). Must be fast because it's updated after each commit(), so we cannot process the entire file. <p>If a file is being ...
  • <div><p><code>account.realm</code> is an only-lightly-normalized form of whatever the user typed in; what little normalization is done does not include case-folding. <p>On the other hand, based on ...
  • <h2>Goals <p>It would be nice to be able to open realm files from Finder or command line. <h2>Expected Results <p>Open my database in Realm Studio after double ...realm/realm-object-server</p></div>
  • Realm数据库冲突

    2020-11-21 15:53:48
    Type io.realm.DefaultRealmModule is defined multiple times: /Users/zhou/workspace/android/JDXL/app/build/intermediates/project_dex_archive/AliyunDebug/out/io/realm/DefaultRealmModule.dex, /Users/zhou/...
  • Realm.createCompartment({ rejectImportExpressions: false, rejectSomeDirectEvalExpressions: false }) // a root realm having only rejectImportExpressions and htmlComments enabled Realm.makeRootRealm({...
  • API for delete Realm file

    2020-11-22 05:48:37
    <div><p>There is a java api for delete all Realm files <code>.realm</code>/<code>.lock</code>/files under management folder. The API simply check if there is no any instances opened in the java side, ...

空空如也

1 2 3 4 5 ... 20
收藏数 10,325
精华内容 4,130
关键字:

realm