Brosef
Brosef

Reputation: 3095

Object variable and Object syntax

if I have the following in my main file

int main ( int argc, const char * argv[])
    {
        @autoreleasepool
        {
            Complex * c1 = [[Complex alloc] init];
            Complex * c2 = [[Complex alloc] init];

            Complex * compResult;

            compResult = [c1 add: c2]; 
            [compResult print];
        {

         return0;        

    {

/**implementation of add method **/
-(Complex *) add: (Complex *) f
{
    Complex *result = [[Complex alloc] init]
    result.real = real + f.real;
    result.imaginary = imaginary + f.imaginary;
    return result;
} 

I know that c1 and c2 are objects, but is compResult considered a variable until we do compResult = [c1 add: c2];

My assumption here is that the add method returns an Object and by doing compResult = [c1 add: c2]; we are setting compResult equal to that object. So does that turn compResult into an object?

So in my mind compResult is a variable that receives the result of the [c1 add: c2], but when we do [compResult print], I get really confused because i thought you can only use this syntax when sending a message (in this case print) to an object?

I guess my main question is after we do compResult = [c1 add: c2]; is the variable compResult holding/representing an object or does it actually become the object????

Upvotes: 1

Views: 78

Answers (2)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726809

Neither c1 nor c2 are objects - both of them are references to objects *, as indicated by the asterisk in their declarations. The difference between them and compResult is that they both are initialized at the time they are declared, while compResult is initially uninitialized.

After the assignment compResult holds a reference to the object allocated inside the add method. Under ARC, the variable is considered __strong by default, meaning that the result object will be released when compResult goes out of scope.


* Technically, c1 and c2 are pointers, but since in ARC-enabled code they acquire special powers to retain and release the objects to which they point, I called them "object references".

Upvotes: 1

Carl Norum
Carl Norum

Reputation: 225032

c1 and c2 are not objects, they're pointers to objects. Similarly, compResult is also a pointer, but at the time of its declaration it's uninitialized, meaning it doesn't point to any specific object.

When you invoke the add: method via [c1 add:c2], a new object is created and a pointer to it is returned. That pointer is assigned to compResult. compResult is still just a pointer, exactly like c1 and c2, but now it points to this newly created object, meaning you can send messages to that object (like [compResult print]) just like you did with [c1 add:c2] before.

Editorial note: it would be more idiomatic to return an autoreleased object from add: rather than the retained one you're using right now.

Upvotes: 3

Related Questions