pete
pete

Reputation: 3050

Is an Object the same as an instance of a Class?

I’m learning Objective-C and I’m confused on what the difference is between an instance of a class and an object –- are they the same ?

Heres an example:

 NSString *name = [[NSString alloc]initWithString:@"Harry"]; 

*name is a pointer to the NSString class. @"Harry" is the value of the string. So is name an Object from the NSString class or is name called an instance of a class?

Another example from a Class I made:

  Rectangle *rect = [[Rectangle alloc]init];  

So *rect is a pointer. Is rect an Object or is it an instance of a class ?

Upvotes: 2

Views: 1709

Answers (4)

Alex Wayne
Alex Wayne

Reputation: 187034

In ObjectiveC, an instance of a class is always an object. And an object is always an instance of a class. An "object" is an instance of a class, a class which somewhere down the chain eventually inherits from NSObject. When you declare a class with no superclass, NSObject is the implicit superclass.

NSString *name = [[NSString alloc] initWithString:@"Harry"]; 

name is a pointer to an object, which more specifically is an instance of NSString that has a value of "Harry". All NSString's are objects.

Rectangle *rect = [[Rectangle alloc] init];

Same here. rect is a pointer to an object, which is an instance of Rectangle.

Upvotes: 4

Matt
Matt

Reputation: 31

Thanks for all your answers but I'm still a little bit confused. So are we saying *rect is just a pointer. rect is the Object (which is an instance from the Rectangle class). Memory is allocated to rect.

@pete yes you have it correct.

Upvotes: 1

Matt
Matt

Reputation: 31

A pointer is not an object. It is simply an address in memory where the object is allocated (stored). Hence, it points to the object. Pointers are in fact a C-language construct, which Objective-C inherits (pardon the pun). Julius is correct that you will hear them interchangeably used, technically "rect" is the instance/object and "*" conveys pointer-to.

Upvotes: 2

jscs
jscs

Reputation: 64002

So *rect is a pointer. Is rect an Object or is it an instance of a class ?

It is both. An instance of a class is also an object, just as the McIntosh that I just finished eating is an instance of the "class" Apple, and is also a fruit.

"Object" is a generic term for a programming structure that keeps some state (its instance variables) and (generally) can perform actions that affect that state (its methods). An instance of a class is a specific object.

In Objective-C, objects are accessed via pointers; that's just the mechanism by which you interact with them. Strictly speaking, the object itself and the pointer to the object are distinct: rect is a pointer to an object, an instance of class Rectangle, but in everyday language, you might see people talking about them in the same way: rect is a Rectangle.

Upvotes: 3

Related Questions