7

So I am using Realm with Swift and I marked my class with the @objcMembers keyword however when I tried to make some private variables, Xcode forced me to add @objc beside those private vars. Is this an intended behavior? Seems like it's redundant to me.

@objcMembers class MyObject: Object {
    @objc dynamic private var text: String = String()
    @objc dynamic private var youtubeLink: String = String()
    @objc dynamic private var count: Int = 0
    dynamic var isFavorite: Bool = false
    dynamic var currentCount: Int = 0
}
2
  • can you post your code
    – A.Munzer
    Apr 29, 2018 at 8:38
  • @A.MunzerI added my code
    – Tarek
    Apr 29, 2018 at 8:43

1 Answer 1

10

The problem is that while @objMembers exposes your members to Objective-C, private hides them again. Thus, to undo that hiding, you have to say @objc explicitly.

To see that this is true, try the following test:

@objcMembers class MyObject: NSObject {
    func f() {
        print("howdy")
    }
}
let c = MyObject()
c.perform(Selector("f"))

That works. But this crashes:

@objcMembers class MyObject: NSObject {
    private func f() {
        print("howdy")
    }
}
let c = MyObject()
c.perform(Selector("f"))

To fix the crash without taking away the private, we have to expose f to Objective-C explicitly:

@objcMembers class MyObject: NSObject {
    @objc private func f() {
        print("howdy")
    }
}
let c = MyObject()
c.perform(Selector("f"))

The only interesting thing about your particular case is that the compiler noticed the problem, instead of letting you just crash as in the second example above. That's because of the dynamic marking, which makes no sense unless we are exposed to Objective-C.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.