iOS
Accessing private properties using NSPredicate [swift][iOS][Realm]

Accessing private properties using NSPredicate [swift][iOS][Realm]

import RealmSwift
class Tag: Object {
    @objc dynamic private var name = ""
}

Let’s suppose you have private property like I mentioned above. Now you might think, `name` property is not accessible right? But you are wrong. It can be accessed using NSPredicate. Here is an example how you can access that private property.

let predicate = NSPredicate(format: "name == 'something'")
let tags = smRealm.objects(Tag.self).filter(predicate)

Run this code and ?boom?. You can still access private access using `NSPredicate` approach.

Well, this is just to let you know that sometime, you might need this idea. You don’t know where you might need it. No problem, let me explain that ?.

Suppose you want to make some properties private and want to access it using getter and setter approach. Let me show you an example adding some codes in above example.

import RealmSwift

enum EType: String {
    case apple = "Apple" 
    case microsoft = "Microsoft"
    case none = ""
}

class Tag: Object {
    var color = "black"
    @objc dynamic private var _name = ""
    var name: EType {
        set { self._name = newValue.rawValue }
        get { return EType(rawValue: self._name) ?? .none }
    }
}

This is something you might want to have in your code to make _name property private. And to access _name, we have introduced Enum properties (name). While using realm objects, you can only access properties created using `@objc dynamic` if you want to use NSPredicate. Here is an example where you cannot access `color` property using NSPredicate.

let predicate = NSPredicate(format: "color == 'black'")
let tags = smRealm.objects(Tag.self).filter(predicate)

This code will crash because NSPredicate cannot find `color` property in Tag class. You can only access properties with `@objc dynamic` variables if you are working with Realm objects. So, what can be done here if you want to make `_name` private but also want to filter object based on tag name. Well, the technique is what I have shown you at top of this post. Let me show you.

let predicate = NSPredicate(format: "_name == 'something'")
let tags = smRealm.objects(Tag.self).filter(predicate)

You can still access private properties from NSPredicate. This code won’t crash because, we do have _name property in Tag class. This way you can make _name private but can access at the of need using NSPredicate.

Hope this is helpful to you. While doing my projects I figure it out.

Thanks for reading my blog guys.

Happy coding.

Leave a Reply