user2453876
user2453876

Reputation: 303

IOS - memory management pointers

I have a question about how best to manage array pointers to ensure no memory leaks happen. I have a container class A and a composited class B. Both have an array property, and both do their own thing to the array. But the container is the only class exposed to the public API. so I set classA.someProperty and it internally sets classB.someProperty like below. What kind of cleanup work do I need to do? Will ARC take care of this for me automagically?

class A

 @property(nonatomic,strong) NSMutableArray* someProperty;
 @property(nonatomic,strong) ClassB* classB;


Class B

 @property(nonatomic,strong) NSMutableArray someProperty;

and in the implementation in Class A;

classB.someProperty = [self.someProperty mutableCopy]
//do some other work with self.someProperty

and in the implementation in Class B;
//do some work with self.someProperty [Includes modifications to the array]

Upvotes: 0

Views: 157

Answers (1)

rakmoh
rakmoh

Reputation: 2963

You don't need to write any cleanup code, ARC will take care of releasing the memory. ARC will automatically put the code to decrement the reference count for variables defined as strong properties.

I would recommend you think in terms of reference count for a variable to understand the memory management. ARC will automatically insert the statements to decrement the reference count at proper places. Lets consider two scenarios for your example:

Scenario 1

No other class has a variable referencing class A's someVariable: when class A reference counts becomes 0 then you can be sure that ARC has put the code to make someVariable reference count 0 (in class A's dealloc).

Scenario 2

Another variable (say in Class C) that is referencing Class A's someVariable then reference count of someVariable will still be decremented (by the code inserted by ARC) but it won't be zero so it won't be released (and that is what you want because you want to access it in Class C).

Upvotes: 1

Related Questions