Retain Loops and Delegates

Guides | Tutorial By 5 years ago

When using delegates in an object in Objective-C it is important that the delegate is only assigned within your object, and never retained. The reason for this is to prevent a retain loop, where two objects retain each other; they will never be released. The fix is simple, but can catch you off guard if you want to create an array or dictionary of delegates (using an NSDictionary orĀ NSArray).

When you add an object to an array it gets retained, when you remove the object from the array it is released. If you use an array of delegates you will need to avoid adding the delegate into the array directly, and use a container class. You can build your own, but there’s no need, Apple has one for you. Add an [NSValue valueWithNonretainedObject:obj] into your array instead, the NSValue will be retained but your delegate will not. Remember to have your delegate remove itself from the delegate list when it is deallocated. To get the delegate back use id delegate = [[delegateArray objectAtIndex:0] nonretainedObjectValue];