iOS memory management

– All objects have a property retaincount.

– copy, new, alloc and retain increase retain count by 1.

– release decreases retain count.

-autorelease decreases retaincount when the current run loop gets finished.

– Can create your own autorelease pools and drain them to reclaim memory.

Zones: Without zones small and large objects will be created together causing fragmentation. With zones, system creates two different zones – separate ones for different sizes of objects.

– Objects returned by Cocoa are normally autoreleased.

-in dealloc : [aProperty release]

or [self.property = nil]

bugs : app crash: something has been released or auto released and is being accessed

memory leak : memory was allocated but hasn’t been reclaimed even though not required

With ARC : Memory gets deallocated when all strong variables pointing to it are deallocated.

Strong, weak and unsafe_retained:

Strong : Valid till runtime and automatically released. Default for all local variables.

Weak : Zeroes ( sets to null ) the weak reference . So if a weak property points to a strong property and the strong property is released – the weak property is set to null.

unsafe_retained: Doesn’t get set to nil but set to a dangling location in memory.

While declaring them inline, use double underscore ..

__strong etc.

Why is weak needed: To avoid circular references.

[obj1 setObject:obj2]

[obj2 setObject:obj1]

Now both have circular references



Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s