返回对象域不可访问

时间:2017-01-25 15:14:17

标签: ios swift realm

我遇到了一个在Realm中返回我的对象​​的问题,奇怪的是,如果我打开控制台对象,如果我启动它但是如果我尝试访问它的值它会告诉我它是空。

对象的结构如下:

class Favourite : Object {
    var character : Character!
}
  1. 我创建了一个对象并将其添加到DB

    let fav = Favourite()
    fav.character = character
    FavouriteDao.sharedInstance.addFavourite(characterFavourite: fav)
    
  2. 获取所有喜欢类型的对象

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

  3. 当我拿到物品并进行打印时

    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. 如果我尝试访问该字符元素,它会告诉我 nil

  5. 有人设法理解,因为如果我打印出喜欢的对象,它会告诉我内部有一个角色对象但是如果我尝试加入它就会说它不存在?

1 个答案:

答案 0 :(得分:1)

你从一开始就做错了。您应该首先阅读领域文档。 https://realm.io/docs/swift/latest/#getting-started

例如。

class Favourite : Object {
    var character : Character!
}

不是你应该在Realm中做的事情。

假设您的Character定义明确,代码至少应为dynamic var character : Character? = nil