Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

difference between NSObject and Struct

Tags:

struct

swift

ios8

I want to know the difference between the NSObject and struct..Following example will explain both cases

In struct

struct UserDetails{
    var userName:String
    var userID:String
    var userAge:String
    func userDescription()->String{
        return "name " + userName + "age " + userAge
    }
}

In NSObject Class

class UserDetails: NSObject {
    var userName:String?
    var userID:String?
    var userAge:String?
    func userDescription()->String{
        return "name " + userName! + "age " + userAge!
    }
}

Can you anyone please tell me where I have to use NSObject class, where I have to use struct..?

like image 835
Mani murugan Avatar asked Jun 24 '14 07:06

Mani murugan


People also ask

What is an Nsobject?

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.

What is difference between class and struct in IOS?

Structs are value types and that means that every change on them will just modify that value, Classes are reference types and every change in a reference type will modify the value allocated in that place of memory or reference.

What's the difference between struct and class Swift?

In Swift, structs are value types whereas classes are reference types. When you copy a struct, you end up with two unique copies of the data. When you copy a class, you end up with two references to one instance of the data. It's a crucial difference, and it affects your choice between classes or structs.

Whats the difference between a class and a struct?

Difference between Structs and Classes: Struct are value types whereas Classes are reference types. Structs are stored on the stack whereas Classes are stored on the heap. Value types hold their value in memory where they are declared, but a reference type holds a reference to an object in memory.


1 Answers

1) Structs are passed by value, Class instances by reference 2) Classes can be subclassed, Structs can't.

Whether or not the Class is a subclass of NSObject is (mostly) irrelevant. You could equally have said:

class UserDetails {
    var userName:String?
    var userID:String?
    var userAge:String?
    func userDescription()->String{
        return "name " + userName! + "age " + userAge!
    }
}
like image 104
Grimxn Avatar answered Oct 13 '22 18:10

Grimxn