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

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


Tag: realm

Hi everyone,

I encounter a little problem with Realm, I have a class "Contact" and a subclass "Person" defined as :


#import <Realm/Realm.h>
#import "Contact.h"


@interface Person : Contact

@property NSString * nickName;


I have an other entity called "Address" which has a "Contact" property ( an address can only be related to one contact ).


#import <Realm/Realm.h>
@class Contact;


@interface Address : RLMObject

@property NSString * city;
@property NSString * country;

@property RLMContact *contact;


The problem is : when I try to set a "Person" object to the contact property of "Address", I got this error :

[address setContact:person];
'Can't set object of type 'Person' to property of type 'Contact'

I tried to cast it but still the same issue :

[address setContact:(Contact *)person];
'Can't set object of type 'Person' to property of type 'Contact'

I even tried after defining the Person class on my Address.h but still the same problem :


#import <Realm/Realm.h>
@class Contact;
@class Person;


@interface Address : RLMObject

@property NSString * city;
@property NSString * country;

@property RLMContact *contact;


Anyone has an idea ?

Thanks in advance guys.


In Realm, while you can subclass your RLMObject entities, those subclasses aren't polymorphic. That is to say, you cannot substitute a Person object when you say you're linking to a Contact object, because Realm treats them as entirely separate entities.


How to have List property?

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).

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

I have followed the steps provided to add the framewowrk from this link 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...

Getting NullPointer adding object to RealmList

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;...

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

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...

Return unique/distinct values with Realm query

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...

Using Reflection with Realm (Android)

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...

RETROFIT POST Realm object

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( .observeOn(AndroidSchedulers.mainThread()) .subscribe(...); I get the following error: > retrofit.RetrofitError: com.fasterxml.jackson.databind.JsonMappingException: Realm access from incorrect thread. Realm...

Refreshing multiple Realm instances at once?

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...

Realm not writing correctly

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 ( 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...

Realm access from incorrect thread Android

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...

How to reproduce MATCHES in NSPredicate to query 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...

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

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...

Multiple Realms with multiple data models

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...

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

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...

Can I store objects from android SDK like Location?

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 error: Invalid Value, expecting int and receiving: 0

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...

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

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

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

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 - Add file with initial data to project (iOS/Swift)

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...

RealmBaseAdapter with section headers

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...

Delete all data from specific Realm Object Swift

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...

Limit number of calls in using Parse

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 & as online Db. Example I'm building the database model and trying to link all many-to-many relations....

Retrofit and Realm access from another thread in Android

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.... Query with GroupBy

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

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...

Correct way to retrieve a single object from Realm database

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...

Encryption in Realm gives java.lang.IllegalStateException: Wrong key used to decrypt 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: public class DatabaseHandlerRealm { private Realm realm; byte[] key,...

How to make a nested query in 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 swift creates objective c files

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, realm to my project. I hope i got all...

Can I have arrayList of string in realm object android

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...

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

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...

Error on Android Realm copyToRealmOrUpdate when inserting existing records

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...

RealmMigrationNeededException when changing Realm model

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....

Update Realm Object Android

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) { = no; } public String getName()...

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

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... API mapping parent object automatically

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...

authc filter is not calling MyRealm in shiro with spring

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...

Watchkit & Realm 0.92.3

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...

RealmResult Many-Many Relationship With Adapter

I have two models who (with relevant properties) look like this: @PrimaryKey String id; String name; RealmList<Song> songs; @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.objects().filter does not work with Resuts

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...

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

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...

Realm - array of NSString as property?

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...

Realm: How to add two Results<(Object)> in 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?...

Is possible to save Realm documentation for offline reading?

I'm going to vacations this Saturday and I need to have Realm API documentation available for offline reading ( Does it exist somewhere for download? Thanks

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

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...

adding and removing Realm.Object during a migration

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...

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

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!,...

From SQL Foreign keys to Realm References?

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...

Using Realm with Swift on iOS 7

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? ... offline, Parse online - What about users

I'm using Parse for the first time to play around with. I use 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...