1

I understand in the delegate pattern for iOS you want the reference to the delegate to be weak, but if I for instance have this:

@property (nonatomic, weak) NSMutableArray *delegates;

and in this array are instances of

id<myDelegateCallback>

The Array has a strong retain of the items inside.

Do I alloc/init the array inside the class that has this as it's property or do I set the array to an instance owned by another class?

Or is this not a good implementation of the Delegate pattern? I understand I can use Notifications and such, but wanted to know if this would actually work without any ARC issues.

Mark W
  • 3,879
  • 2
  • 37
  • 53
  • You're better off using NSNotification. Otherwise you'll need to write a custom NSMutableArray that does uses weak references, to avoid having your delegates retained by your object. http://stackoverflow.com/questions/4692161/non-retaining-array-for-delegates# – Alan Apr 04 '13 at 00:56

2 Answers2

2

You can only have one designated delegate object, not an array of delegates. Some classes have a delegate AND a "data source" that conform to unique protocols, but that only makes sense for objects that need to get their content from some designated place.

But if you want to notify several listening objects of some thing happening, consider using a NSNotification registered with NSNotificationCenter. The downside is that there's no formal or declared protocol methods for the listeners to conform to (and for the compiler to complain about if there's any issues).

Here's a related question with more useful information.

Community
  • 1
  • 1
Michael Dautermann
  • 88,797
  • 17
  • 166
  • 215
  • Also in my experience, NSNotification was slower than straight delegate message passing. – Alan Apr 04 '13 at 00:55
2

If you really need an array of weak delegates, you can use a bridged CFMutableArray initialized with NULL retain and release callbacks.

See more here: https://developer.apple.com/library/mac/#documentation/CoreFOundation/Reference/CFMutableArrayRef/Reference/reference.html#//apple_ref/doc/uid/20001502

Jacob Relkin
  • 161,348
  • 33
  • 346
  • 320