Reputation: 37581
I'm attempting to use setters to remove the need for calling code to have to use Realm transactions whenever properties of a Realm object are being updated, but without success.
For example suppose I have got the following Realm class:
@interface Caller : RLMObject
@property (strong, nonatomic) NSString * _Nullable name;
@property (strong, nonatomic) NSString * _Nullable number;
@property (assign, nonatomic) int someInt;
@end
With a setter for someInt as below:
@implementation Caller
- (instancetype) init
{
self = [super init];
return self;
}
- (void)setSomeInt: (int) newValue
{
RLMRealm *realm = [self realm];
if (realm)
{
[realm beginWriteTransaction];
}
_someInt = newValue;
if (realm)
{
[realm commitWriteTransaction];
}
}
Now if I create a new object and set someInt then setSomeInt gets called:
Caller* caller = [[Caller alloc] init];
caller.someInt = 8;
Fine, but if the caller object is then saved saved to Realm and then someInt
is changed again, then the following error occurs:
'RLMException', reason: 'Attempting to modify object outside of a write transaction - call beginWriteTransaction on an RLMRealm instance first.'
But this is exactly what the point of setter is trying to prevent - to create a transaction if necessary, but the Realm error is "occurring before" setSomeInt
is getting called in this case. Why is the setter not being called when the object has been stored to Realm, but it is called prior to that, and is there a solution without having to set the property explicitly via a method?
Upvotes: 0
Views: 390
Reputation: 18308
The short answer is that Realm does not support overriding getters and setters for persisted properties.
The reason you observe the behavior that you do is because Realm inserts custom getters / setters for instances of your class that are managed by Realm. These getters / setters are responsible for reading / writing data from the underlying Realm file. The workaround mentioned in the link above (use separate properties that are ignored by Realm for the custom get / set behavior, storing through to a non-ignored property) may work for your purposes.
Upvotes: 0