realm , Assigning property to subclass of RLMObject


Assigning property to subclass of RLMObject

Question:

Tag: realm

I'm trying to use a subclass of a RLMObject as a base class for a property of other subclass of RLMObject, with no luck. Is this a known restriction, or is there a workaround for it?

test.m:

#import <XCTest/XCTest.h>
#import <Realm/Realm.h>

@interface Base : RLMObject; @end
@interface Derived : Base; @end

@interface User : RLMObject
@property Base *obj;
@end

@implementation Base; @end
@implementation Derived; @end
@implementation User; @end

@interface rlmrlmTests : XCTestCase; @end
@implementation rlmrlmTests

- (void) testOK {
    User *user = [[User alloc] init];

    user.obj = [[Base alloc] init]; // OK
    [[RLMRealm defaultRealm] transactionWithBlock:^{
        [[RLMRealm defaultRealm] addObject:user];
    }];
}

- (void) testZFail {
    User *user = [[User alloc] init];

    user.obj = [[Derived alloc] init]; // ERROR
    [[RLMRealm defaultRealm] transactionWithBlock:^{
        [[RLMRealm defaultRealm] addObject:user];
    }];
}

@end

will get an exception saying:

error: -[rlmrlmTests testZFail] : failed: caught "RLMException", "Can't set object of type 'Derived' to property of type 'Base'"


Answer:

That's a current limitation of Realm. It doesn't support polymorphism on relations.

If possible, I'd avoid inheritance in this case. You could reach that by altering your object-relational mapping: You could add a further discriminator column to your Base class and have relations to classes which contain further attributes and wouldn't inherit anymore from the Base class. If you have just one subclass, then a discriminator column is eventually not needed.

@interface Base : RLMObject
@property NSString *discriminator;
@property BaseExtensionA *extA;
@property BaseExtensionB *extB;
@end

@interface BaseExtensionA : RLMObject
// the properties of the prior `Derived` would go here
@end

@interface BaseExtensionB : RLMObject
// …
@end

Related:


RealmResult Many-Many Relationship With Adapter


java,android,realm
I have two models who (with relevant properties) look like this: Playlist.java @PrimaryKey String id; String name; RealmList<Song> songs; Song.java @PrimaryKey String id; String name; As you can see, a playlist can contain many songs, and a song can belong to many playlists. In one portion of my app I...

Realm error: Invalid Value, expecting int and receiving: 0


ios,swift,realm
I am using Realm with Swift for a query, but am receiving this error: Terminating app due to uncaught exception 'Invalid value', reason: 'Expected object of type int for property 'id' on object of type 'JournalEntryLine', but received: 0' The JournalEntryLine class does have a property (Int) named id. The...

Realm.io Removing the realm file


ios,file,realm
My question, how can I properly remove a realm file? Currently I'm doing so using the file manager, which is fine for me since the Realm file is mostly here for offline caching. My app logs in to a web-platform, and creates a realm for this platform so you can...

Can I store objects from android SDK like Location?


android,realm
Can I store objects from android SDK like Location in realm? If so, how can I do it? I am getting this error message Error:(14, 8) error: Type android.location.Location of field location is not supported or what could be a workaround to save a location?

Realm.io API mapping parent object automatically


swift,realm
I am using Realm and its REST API's mapping method to map JSON data to my models and their child relationships automatically. It works great, except when I add in a "To-One" relationship on the child models referencing the parent. The mapping goes all out of whack and creates additional...

Realm.io offline, Parse online - What about users


android,parse.com,realm
I'm using Parse for the first time to play around with. I use Realm.io as a offline db. Both are very powerful and it's great to get to know them better. (Big up to both teams!) My app should be able to be used on remote locations, where you can't...

Can I have arrayList of string in realm object android


java,android,arraylist,realm,realm-list
As we dont have any list data type in realm, how can we use ArrayList<String> in a realm object? I had same question for the arrayLists of the custom models we make i.e. ArrayList<CustomModel> but for that I understand that we first have to make RealmObject of same Custom model...

adding and removing Realm.Object during a migration


swift,migration,realm
I am doing a migration which requires removing objects from the realm and replacing them with a different type. In short, I used to have a single type, and am now creating a hierarchy, so BaseItem now needs to be a DerivedItem. I'm not sure the best way to accomplish...

Realm.io Query with GroupBy


java,android,sql,orm,realm
I want to group some accounts by month, can i do this with Realm.io? public class Account extends RealmObject { ..... private Date date; } RealmResults accounts = realm.where(Account.class) .beginGroup() .equalTo("date", "MONTH(date)")//<----- wrong code .endGroup() .findAll(); thanks...

RealmBaseAdapter with section headers


android,listview,realm
I'm trying to use the realm data store for Android and i'm trying to build an application that shows the user a list of options in a ListView, kind of like the users contact list. The first letter for each section (such as A, B, C, etc.) should be a...

Realm: Module was created by an older version of compiler and could not build objective-c module


ios,swift,realm
I have followed the steps provided to add the framewowrk from this link https://realm.io/docs/swift/latest/ It gives this error what could be the issue? Is it because it is compiled with an older version of xcode, since I have the latest xcode 7 beta? If so, how would I solve...

Return unique/distinct values with Realm query


ios,objective-c,swift,realm
I have a Message/RLMObject model that has a NSString *jabberID property/row and I want to retrieve every unique value inside that row. In other word, I want to retrieve non-repeated jabberID values from my Message model. Can anyone help out figuring this? The way I use to do with coredata...

Realm not writing correctly


ios,swift,cocos2d-iphone,realm
I've been trying to use Realm to create a db for my cocos2d game, but can't figure out some problem. I'm using Realm Objective-C 0.92.3 (https://realm.io/docs/objc/latest/) since I need my game to work on iOS 7 or later. I've been using some small code to write and read but somehow...

Encryption in Realm gives java.lang.IllegalStateException: Wrong key used to decrypt Realm


android,encryption,realm
I am using Encryption in Realm for inserting data into database. I have to insert data into different tables, and tried to encrypt the data in tables. But i just got java.lang.IllegalStateException: Wrong key used to decrypt Realm. My Codes: DatabaseHandlerRealm.java public class DatabaseHandlerRealm { private Realm realm; byte[] key,...

Error on Android Realm copyToRealmOrUpdate when inserting existing records


android,realm
I've started using Realm for Android. I'm lovin' it so far, but I'm having some problems trying to understand how to use correctly the "copyToRealmOrUpdate". I will receive a JSON (that I'm mapping into a Contact RealmObject Array) with a X "contacts" every time I open the App, and I...

Realm - Add file with initial data to project (iOS/Swift)


ios,xcode,swift,realm
I'm developing an application for iOS using swift and chose Realm as a database solution for it. I wrote default data in AppDelegate using write/add function from realm docs and it works just fine. So after first launch I have a *.realm file with my initial data. In Realm documentation...

I have a model class, using which I save to realm. How do I use `contains()` to see if the object has already been stored


java,android,realm
Here's the model class - public class BasicSavedInfoImpl extends RealmObject implements BasicSavedInfo { private String iD; @Override public String getID() { return iD; } @Override public void setID(String ID) { this.iD= ID; } } Here's how I write id to realm - realm.beginTransaction(); BasicSavedInfoImpl basicSavedInfoImpl = realm.createObject(BasicSavedInfoImpl.class); basicSavedInfoImpl.setID(id); realm.commitTransaction(); How...

What's the most efficient way to store time zone info in Realm?


ios,osx,nsdate,realm,foundation
I have a Realm object that contains an NSDate timestamp, representing the time at which a user recorded something. I need to add time zone info to this, so that I know what the local time zone was when the user created the object (in order to do accurate date...

In Java, How do I cast a Realm Object into the class I wish to write to the Database?


android,class,object,casting,realm
I am currently working on a project where my Database has a very large number of tables (Approx 60 total). I am working to create the Database Helper class that will function as the writer/ reader to/ from the database. And example of my write method would be this: public...

Using Reflection with Realm (Android)


java,android,reflection,realm
I made a switch to Realm last week. Now, I've got this issue when using reflection: Normally I'd use reflection to fetch field, which when available I'd use to replace url params in our API url f/e: blog/{blogId}/comments <- not an actual url but an example. The code would check...

Realm swift creates objective c files


objective-c,swift,realm
I just started working with realm in my project. I have a Cocos2D game project, created with spritebilder. The code is in swift, except the appdelegate, which I don't know why, is in objective-c. I just added, folowing thi instructions https://realm.io/docs/swift/latest/, realm to my project. I hope i got all...

From SQL Foreign keys to Realm References?


json,realm
We have a PostgreSQL server-side DB. We download table rows to the tablet through JSON strings. Now we are migrating to Realm and are now facing the Foreign Keys problem right now. How does Realm manage this?. I mean, our shema has a lot of references in many different tables...

authc filter is not calling MyRealm in shiro with spring


java,spring,security,shiro,realm
I'm working on project with spring/hibernate/jax-rs(jersey). I wanted to integrate shiro to my project. I did configurations as in documentation. I have my own implementation of Realm. Q: Problem is when authBasic path is called, it works fine with MyRealm. But when i call for authc(FormAuthenticationFilter) it shows login page...

Multiple Realms with multiple data models


ios,swift,realm
Is it possible to create two different realms each one using a different data model? For example: defaultRealm would use the client class as model and myRealm would use products class as model...

Retrofit and Realm access from another thread in Android


android,multithreading,retrofit,realm
I am using Realm for database service and Retrofit for server service. I want to get data from Realm and pass it as object to Retrofit, but I get following error : retrofit.RetrofitError: Realm access from incorrect thread. Realm objects can only be accessed on the thread they where created....

How can I fix this memory issue in my maximum matching algorithm with RealmSwift?


algorithm,swift,realm,text-segmentation
I wrote my own maximum matching function in Swift to divide Chinese sentences into words. It works fine, except with abnormally long sentences the memory usage goes up over 1 gb. I need help figuring out how to modify my code so that there isn't this memory problem. I'm not...

How to clone a object with primary key in Realm.io (objective-c)


ios,objective-c,realm
i have an object model, with a primary key and i want to do a clone of that object with another primary key but realm.io says "this object already exist " the primary key is not the same as the first object RLMRealm *realm = [RLMRealm defaultRealm]; [realm beginWriteTransaction]; ActivityTreeModel...

Realm.IO - Can JSON array be parsed using createOrUpdateAllFromJson?


android,json,realm
Inside Doctor class, I have RealmList - specializationList. public class Doctor extends RealmObject { @PrimaryKey private String doctorId; private FullName fullName; private Age age; private String organizationId; private Position position; private String category; private String loyalty; private RealmList<Specialization> specializationList; private Contacts contacts; private String key; .... Specialization class public class...

Getting NullPointer adding object to RealmList


android,realm
I have a problem when I try to add a new object to RealmList in Realm database Android. Always I'm getting NullPointer error at: Global.USER_LOGGED.getProductsGrid().add(pFinal); This is my models: @RealmClass public class UserRealm extends RealmObject implements Serializable { private String email; private String password; private String tokenId; private String tokenSecret;...

RETROFIT POST Realm object


android,retrofit,realm
I have the following RETROFIT API: @POST("/payments") Observable<Response> saveCreditCard(@Body CreditCard creditCard) CreditCard is a RealmObject. When I try to use my API method: CreditCard card = realm.createObject(CreditCard.class); card.setWhateverField(...); ... mApi.saveCreditCard(card) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(...); I get the following error: > retrofit.RetrofitError: com.fasterxml.jackson.databind.JsonMappingException: Realm access from incorrect thread. Realm...

Using Realm with Swift on iOS 7


ios,swift,ios7,realm
I have an app written in Swift that supports iOS 7. I want to use Realm for my database, but according to their documentation the Swift library supports iOS 8 only. I don't want to write Objective-C code in my app. Is there any way around this? ...

Limit number of calls in using Parse


android,database,many-to-many,realm
I'm building my first application with a backend. General info The app allows users to upload a place, attach tags to it, pictures, etc. Dbs I'm using Realm as an offline Db & Parse.com as online Db. Example I'm building the database model and trying to link all many-to-many relations....

realm.objects().filter does not work with Resuts


swift,realm
I tried to do query objects from Realm using RealmSwift framefowk with predicates: realm.objects(Train).filter("ANY route IN %@", realm.objects(Route)) Error is: Cannot invoke 'filter' with an argument list of type '(String, Results)' The same code worked with Realm framework but does not work with RealmSwift framework. What am I doing wrong...

Realm access from incorrect thread Android


java,android,multithreading,realm
I am dealing with this issue on Android : Realm access from incorrect thread. Realm objects can only be accessed on the thread they where created. I want to use Realm in my RemoteViewsFactory with public class RemoteViewsX implements RemoteViewsFactory { public RemoteViews getViewAt(int paramInt) { if (this.results != null...

If I make a database on Realm, will it be accessible to my user without internet access?


ios,realm
I'm trying to build my first Swift app and I think Realm may be a good option for my database. This might be a totally stupid question, but will my users be able to access the data on my database without an internet connection? I'm fairly certain that the answer...

Watchkit & Realm 0.92.3


ios,watchkit,realm
The Swift integration of a new Realm-DB (realm 0.92.3) under Xcode 6.3 and iOS10.10.3 basically works for the iPhone (not for the Apple-Watch yet). The integration of the same realm-framework under Watchkit (i.e. Apple-Watch) does not work yet. The RealmSwift.framework is integrated (dragged into) the Embedded-Binaries as described here1 and...

Realm - array of NSString as property?


realm
Hi everyone, I'm working with Realm and I'd like to add an NSArray as one of my RLMObject's properties. I just want to store NSString in that Array, that's why I don't want to define a RLMArray property ( I don't want to create a new RLMObject equivalent to an...

How to have List property?


ios,swift,realm
How do I have a List property in a Realm object? I want to save the strings to the same object not to have related objects each having a single string (which I assume happens if I use some StringWrapper class).

Delete all data from specific Realm Object Swift


swift,persistence,realm
Before i get too far into my question. My goal, which may influence your answers, is to remove Object data if it is no longer in the cloud. So if I have an array ["one", "two", "three"] Then in my server I remove "two" I want my realm to update...

How to reproduce MATCHES in NSPredicate to query Realm?


regex,nspredicate,realm
I have a query using NSPredicate that takes regular expression and matches to paths: let predicate = NSPredicate(format: "path MATCHES '/test/([^/]*[^/])$'") which matches everything inside folder test but excludes all subfolders of folders in test, like this: /test/abc -> yes /test/abc/def -> no The problem is, that I can't use...

Update Realm Object Android


android,realm
I have VisitingCardPOJO form table I want update single entry say where no=3 VisitingCardPOJO .java public class VisitingCardPOJO extends RealmObject { @PrimaryKey private int no; private String name; private String address; public int getNo() { return no; } public void setNo(int no) { this.no = no; } public String getName()...

RealmMigrationNeededException when changing Realm model


android,realm
Whenever I change the model like adding more fields, the app crash with io.realm.exceptions.RealmMigrationNeededException error. This can only be resolved when I uninstalled and reinstalled the app. Any suggestion to do migration? I am using only the default instance....

How to make a nested query in Realm?


realm
I have two realms: public class ChatRealm extends RealmObject { private String id; private RealmList<UserRealm> users; } public class UserRealm extends RealmObject { private String id; private String username; } I have an User id and I want to know which chats he is participating in. I have check the...

Realm - Can't set object of type subclass to property of type parent class


realm
Hi everyone, I encounter a little problem with Realm, I have a class "Contact" and a subclass "Person" defined as : Person.h #import <Realm/Realm.h> #import "Contact.h" RLM_ARRAY_TYPE(Person) @interface Person : Contact @property NSString * nickName; @end I have an other entity called "Address" which has a "Contact" property ( an...

Realm: How to add two Results<(Object)> in Realm


ios,swift,realm
For arrays we could just do resultArray = array1 + array2 I have two results of Results<(Object)> how do I add them? Do I have to loop or is there in any other way?...

How to migrate Realm object that hasn't been stored?


ios,swift,migration,realm
I have an object that I haven't stored anywhere (yet). Even without creating a Realm for it, the app crashes saying this object requires a migration after I've modified it. I've tried this (in method func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool): RLMRealm.setSchemaVersion(1, forRealmAtPath: RLMRealm.defaultRealmPath()) { (migration: RLMMigration!,...

Correct way to retrieve a single object from Realm database


database,swift,realm
I am absolutely loving Realm (0.92) in combination with Swift but have a question about reading an object from the database. My goal is to retrieve a single object with a known, unique ID (which also happens to be the primary key. All the documentation appears to be oriented around...

Refreshing multiple Realm instances at once?


java,android,multithreading,realm,event-bus
I'm using a setup in which every Presenter that is a retained Fragment has its own Realm instance. However, this essentially means that these Realms are all on the main thread. Now that also means, if I want to modify the Realm, I either need to do that on the...

Is possible to save Realm documentation for offline reading?


android,ios,documentation,realm
I'm going to vacations this Saturday and I need to have Realm API documentation available for offline reading (https://realm.io/docs/swift/latest/api/index.html). Does it exist somewhere for download? Thanks

RealmSwift error: “RLMException, reason: Collection was mutated while being enumerated.”


swift,nspredicate,enumeration,realm
I am getting the following error: "RLMException, reason: Collection was mutated while being enumerated." I get the error when I try to do this: let realm = Realm() let words = realm.objects(Word).filter("ANY collectedSentences.characterCount > 0") realm.write { for word in words { word.collectedSentences.removeAll() } } I don't get that error...