Alejandro
Alejandro

Reputation: 325

Return object realm not accessible

I'm having problems with an object that returns me in Realm, the strange thing is that if I printo console the object if I start it well but however if I try to access its value it tells me that it is empty.

The structure of the object is as follows:

class Favourite : Object {
    var character : Character!
}
  1. I create an object and add it to the DB

    let fav = Favourite()
    fav.character = character
    FavouriteDao.sharedInstance.addFavourite(characterFavourite: fav)
    
  2. Get all objects of favorite type

    func getAllFavourites() -> Results { return realm.objects(Favourite.self) }

  3. When I get the item and do a print

    Favourite {
    character = Character {
        name = Spider-Man;
        descriptionC = Bitten by a radioactive spider, high school student Peter Parker gained the speed, strength and powers of a spider. Adopting the name Spider-Man, Peter hoped to start a career using his new abilities. Taught that with great power comes great responsibility, Spidey has vowed to use his powers to help people.;
        thumbnail = Thumbnail {
            id = 815D93D0-C116-4267-978C-9E47C0074D0D;
            path = http://i.annihil.us/u/prod/marvel/i/mg/3/50/526548a343e4b;
            extensionImage = jpg;
        };
    };
    
  4. If I try to access the character element it tells me that it is nil

Somebody manages to understand because if I make a print of the favorite object it shows me that there is inside a character object but nevertheless if I try to accede to it it says that it does not exist?

Upvotes: 0

Views: 271

Answers (1)

Owen Zhao
Owen Zhao

Reputation: 3355

What you do is totally wrong from the very beginning. You should read the realm docs first. https://realm.io/docs/swift/latest/#getting-started

For example.

class Favourite : Object {
    var character : Character!
}

is not something you should do in Realm.

Assuming your Character is well-defined, the code should be dynamic var character : Character? = nil at least.

Upvotes: 1

Related Questions