Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why would I need to use NSObject?

Tags:

swift

swift3

I am confused about why I would need to use NSObject in Swift 3. If so, please guide me also is it best practice to use NSNumber?

    class App: NSObject {
            
            var id: NSNumber?
            var name: String?
            var category: String?
            var imageName: String?
            var price: NSNumber?
            
            var screenshots: [String]?
            var desc: String?
            var appInformation: AnyObject?
            
           // override func setValue(_ value: Any?, forKey key: String) {
           //     if key == "description" {
           //         self.desc = value as? String
           //     } else {
           //         super.setValue(value, forKey: key)
           //     }
           // }
            
        }

Note: Could you tell me why I need to use NSObject? What is the advantage?

like image 463
cristan lika Avatar asked Oct 25 '25 06:10

cristan lika


1 Answers

NSObject class:

This class is the root class of most Objective-C class hierarchies, from which subclasses inherit a basic interface to the runtime system and the ability to behave as Objective-C objects. (source).

AnyObject protocol: its a implicit confirmation of any object.

You use AnyObject when you need the flexibility of an untyped object or when you use bridged Objective-C methods and properties that return an untyped result. AnyObject can be used as the concrete type for an instance of any class, class type, or class-only protocol.

AnyObject can also be used as the concrete type for an instance of a type that bridges to an Objective-C class.

let s: AnyObject = "This is a bridged string." as NSString
print(s is NSString)
// Prints "true"

let v: AnyObject = 100 as NSNumber
print(type(of: v))
// Prints "__NSCFNumber"

The flexible behavior of the AnyObject protocol is similar to Objective-C’s id type. For this reason, imported Objective-C types frequently use AnyObject as the type for properties, method parameters, and return values. (source)

So you can use NSNumber variable as AnyObject which can be later type cast implicitly accordingly.

like image 184
vaibhav Avatar answered Oct 26 '25 21:10

vaibhav