Ankit Bhatt
Ankit Bhatt

Reputation: 11

What is the actual difference between an 'object' and a 'variable' in Objective-C?

I would like to ask a question, about an 'Object' and 'variable' in Objective-C. As we know, we can take many variables to store data of an object, but first we have to create an object with allocation. We have to give a memory location for our object in RAM using 'alloc' keyword. I think object can't store data because, an object is a noun, like a person. So, to store a data we need to use a variable. In C or C++ we use a variable of any primitive data type for data storage purpose. In Objective-C we use predefined classes like NSString.

So, can I use a variable with my NSString class type or I will use only an object with class type object.

There are two problems for me.

NSString *xyz = [[NSString alloc] init]; // can anyone tell me what should be 'xyz' in here a 'variable' or an 'object'?

if 'xyz' is an object in here. So, firstly I have to create it. But somewhere I have seen like....

NSString *xyz = @"welcome"; // according to me, here we are not allocating memory for 'xyz'. Why?

What is the difference between both statements? Can you please tell me?

Upvotes: 0

Views: 110

Answers (1)

gnasher729
gnasher729

Reputation: 52592

Objects are instances of classes. (And that's all there is. Nothing else needs saying).

Variables are global and static variables (having unlimited life times) and automatic variables (variables existing while a function is executing, or while a new scope in a function is entered), and disappearing when the scope ends or the function returns.

In Objective-C, objects can never be variables. Pointers to objects can be variables, but objects can't. Values that are part of an object are often called "instance variables", but that is not the same as a variable.

In other languages, like C++, objects can be variables. The question "what is the difference between objects and variables" doesn't really make sense. It's like asking "what's the difference between alcohol and a cow". They are different categories of things.

@"MyString" is a shortcut; the compiler will create an object for you and give you a pointer to that object.

Upvotes: 1

Related Questions