Why is my Realm object not saving stored values?

后端 未结 2 946
野性不改
野性不改 2021-01-21 07:15

I was browsing around looking for a solution to implement a small offline data storage in one of my apps which would be easy and quick to use. Anyways, I came across with Realm

2条回答
  •  无人及你
    2021-01-21 07:54

    The problem with your realm object is that you are not querying realm for your object. Rather, you are only allocating a new iReciptDataBase object. You will first need to add a property to that object so that you will be able to query for it, something like databaseId shown here:

    @interface iReceiptDatabase : RLMObject
    @property NSString *receiptNo;
    @property NSString *databaseId;
    @end
    
    @implementation iReceiptDatabase
    @end
    
    RLM_ARRAY_TYPE(iReceiptDatabase)
    

    Then in your viewDidLoad, you first query the realm file for an existing object, then only after not finding it, you would allocate it:

    - (void)viewDidLoad {
        [super viewDidLoad];
    
        RLMRealm *realm = [RLMRealm defaultRealm];
        iReceiptDatabase *myDatabase = [[iReceiptDatabase objectsWhere:@"databaseId = '1'"] firstObject];
    
        if(!myDatabase) {
            [realm beginWriteTransaction];
            myDatabase = [[iReceiptDatabase alloc] init];
            myDatabase.receiptNo = @"1";
            myDatabase.databaseId = @"1";
            [realm addObject:myDatabase];
            [realm commitWriteTransaction];
        }
    
        //...
    }
    

提交回复
热议问题