Objective-C pointers?

2019-02-04 16:03发布

I am new to coding and trying to get up to speed with Objective-C. Came across some code I did not understand. I was hoping someone could clarify it for me. In the case below, I am not sure how *foo2 is working and why it is not being released?

ClassOne *pointer = [[ClassOne alloc]init];

ClassTwo *foo = [[ClassTwo alloc]init], *foo2; 

 foo2 = [foo add: pointer];
 [foo release]; 
 foo = foo2

[pointer release];

[foo release];

7条回答
叼着烟拽天下
2楼-- · 2019-02-04 16:29
ClassOne *pointer = [[ClassOne alloc]init];

The variable pointer is a pointer to an object of class ClassOne. It it assigned the value of a newly created object.

ClassTwo *foo = [[ClassTwo alloc]init], *foo2;

*foo and *foo2 are objects of class ClassTwo. Only foo is assigned a newly created object. foo2 may point to anything, so it is unsafe to use it before assigning it a value.

 foo2 = [foo add: pointer];

foo2 is assigned a value: I assume that the add: message of class ClassTwo creates an object (the signature of the method should be -(ClassTwo*)add:(ClassOne*);)

 [foo release];

The object pointed to by foo is no longer needed.

 foo = foo2;

The variable foo is assigned the value of foo2: both point to the same object.

[pointer release];

The object pointed to by pointer is no longer needed.

[foo release];

The object pointed to by foo (and also by foo2) is no longer needed.

查看更多
登录 后发表回答