неділя, 14 серпня 2011 р.

Objective-C memory management - copy method and retain cycles

I've been hunting for memory leaks in the Jets project this afternoon. One of the things I love so much about programming is that you keep finding new and amazing things day after day.

While trying to remove a leak today, I found out that copy method of immutable objects complying to NSCopying protocol may not actually copy. Sounds weird? It just doesn't make a copy of the object but rather returns same object with incremented retain count.
According to this article - Assign, retain, copy: pitfalls in Obj-C property accessors - this behavior is immanent to NSString immutable class. Well, why do you need a copy of an NSString if it's immutable and its content cannot change?

Another article I would like to recommend in connection with my leaks-hunting is Rules to avoid retain cycles from the same Cocoa with Love blog. I can remember reading it two years ago but it's still fresh and important. I think it becomes even more important with the announced compile-time garbage collection in iOS5.