Why is my Realm object not saving stored values?

房东的猫 提交于 2019-12-01 20:30:21

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];
    }

    //...
}

My guess would be viewWillDisappear is never being called. I would recommend committing your write transaction after each change to your data rather than leaving the transaction open as long as the view is visible - instead of adding the object at the end, you could change your other methods to commit the data:

- (void)viewDidLoad {

    self.realm = [RLMRealm defaultRealm]; // property type RLMRealm

    [realm beginWriteTransaction];
    self.myDataBase = [[iReceiptDataBase alloc] init]; // property type iReceiptDataBase
    [realm addObject:myDataBase];
    [realm commitWriteTransaction];

    receiptNumber = [myDataBase.receiptNo intValue];

    NSLog(@"In my realm database(first call) -> %@", myDataBase.receiptNo);
    NSLog(@"In my local app(first call) -> %d", receiptNumber);
}

-(void)drawPDF:(NSString*)fName {

    receiptNumber += 1; // property type int

    [realm beginWriteTransaction];
    myDataBase.receiptNo = [NSString stringWithFormat:@"%d", receiptNumber];
    [realm commitWriteTransaction];

    NSLog(@"In my realm database(second call) -> %@", myDataBase.receiptNo);
}

I would also consider storing receiptNo as an int on your data model.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!