-1

Can anyone tell me what is the difference among three property of delegation. I searched in google but did not get any satisfactory answer. Please also tell me which is the best option and why?

@property (nonatomic, strong) id <GameAddViewControllerDelegate> delegate;
@property (nonatomic, weak) id <GameAddViewControllerDelegate> delegate;
@property (nonatomic, assign) id <GameAddViewControllerDelegate> delegate;
Gajendra Rawat
  • 3,673
  • 2
  • 19
  • 36

3 Answers3

2

The difference is same as with strong, weak and assign specifiers.

Points to be noted : Any object never retains the delegate. Hence strong and retain should not be used.

weak and assign are allowed or even you can go with unsafe_unretained.

Why not to use retain?

Why use weak or assign?

Community
  • 1
  • 1
Anoop Vaidya
  • 46,283
  • 15
  • 111
  • 140
  • Thanks for the answer Anoop. can you tell me in which case I have to use assign or weak – Gajendra Rawat May 19 '14 at 09:56
  • Mostly you use `weak` with delegates. As `assign` simply points to the same value and is frequently used with primitive data types, and delegates aren't. – Anoop Vaidya May 19 '14 at 09:58
2

Weak

weak applies to the delegate object (which has reference counts and all the stuff), but weak references don't increase refcount. But once the delegate object is deallocated (from anywhere in the code), any weak reference to that object is set to nil. This is extremely useful, because if you use only strong and weak references, you can't end up with an invalid pointer (pointer to an already deallocated object).

Assign

assign is usually used for ints, floats and other non-object types. You can of course assign an object reference to such a variable, but if the object is deallocated, you will still have a pointer to it's memory (which is garbage now, and will hurt you when you use it).

Strong

Strong will keep the object in the heap until it don't point to it anymore. In other words " I'am the owner, you cannot dealloc this before i'm fine with that same as retain" You use strong only if you need to retain the object.

In case of delegation, weak preferred

mohamedrias
  • 18,326
  • 2
  • 38
  • 47
0

You generally want to assign delegates rather than retain them, in order to avoid circular retain counts where object A retains object B and object B retains object A. (You might see this referred to as keeping a "weak reference" to the delegate.) For example, consider the following common pattern:

-(void)someMethod {
self.utilityObject = [[[Bar alloc] init] autorelease];
self.utilityObject.delegate = self;
[self.utilityObject doSomeWork];
}

if the utilityObject and delegate properties are both declared using retain, then self now retains self.utilityObject and self.utilityObject retains self.

Also see this detailed answer on stackoverflow

Community
  • 1
  • 1
iAhmed
  • 6,556
  • 2
  • 25
  • 31