swift - 在父类(super class)中使用 className() 来获取 Realm 中子类的名称

标签 swift realm

我在 Realm 中有一个名为 BrowserCategoryObject 子类,以及 ArtistDecade GenreBrowserCategory 的子类。

现在,BrowserCategory 的每个子类都有这个 LinkingObject 属性 songs:

let songs = LinkingObjects(fromType: Song.self, property: "decade") 

(例如,对于 Decade 子类)

我想在 BrowserCategory 基类中编写此内容,因此我尝试了以下操作:

var songs = LinkingObjects(fromType: Song.self, property: className().lowercased())

但是这会返回基类名称而不是子类名称,并给出以下错误:

- Property 'Song.browsercategory' declared as origin of linking objects property 'Decade.songs' does not exist

有没有办法按照我想要的方式做到这一点?

最佳答案

您可能正在寻找 type(of:self),它是多态的,如本演示所示:

class BrowserCategory {
    func className() -> String {
        return String(describing:type(of:self))
    }
}
class Artist : BrowserCategory {}
class Decade : BrowserCategory {}
class Genre : BrowserCategory {}

let a = Artist()
a.className() // "Artist"

但是,我应该提醒您,以字符串形式请求类的名称是一件非常奇怪的事情。更常见的做法是使用类类型作为类型。

关于swift - 在父类(super class)中使用 className() 来获取 Realm 中子类的名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43921197/

相关文章:

ios - 无法在设备上找到 Realm 文件

swift - Realm 对象谓词搜索无效

ios - 沿着路径的点

swift - 雪碧包 : How to limit player movement to certain tiles only

swift - Swift 中的字典值

swift - 如何将自定义排序应用于此对象数组?

ios - UICollectionViewCell 中的 Realm 对象级通知

ios - RLMException - 在 TableView 中滚动时对象已被删除

ios - 你能从 IOS 中的 assetURL 获取图像文件名吗?

ios - UIButton 在第一次运行时工作正常,但在模拟器上第二次运行时不起作用