1

As we know, we will declare a delegate object with weak that can break strong reference cycle:

// MyObject.h

...

@property (nonatomic, weak) id<MyDelegate> delegate;

...

// ViewController.m

...

 self.myObject.delegate = self;

...

and I want to know: can we declare delegate with strong, and set a weakSelf to it:

// MyObject.h

...

@property (nonatomic, strong) id<MyDelegate> delegate;

...

// ViewController.m

...

__weak typeof(self) weakSelf = self;
self.myObject.delegate = weakSelf;

...
Kim Jin
  • 180
  • 1
  • 8
  • you _could_ but you are supposed not to create potential strong reference cycles deliberately; it seems logically the `weakSelf` immediately has got a `strong` reference when you assigned it to your `strong` property. – holex Jul 18 '17 at 13:30
  • Does it will cause reference cycle? – Kim Jin Jul 19 '17 at 01:53
  • as long as you are having a `strong` pointer, you _could_ create a strong-reference cycle in that case. – holex Jul 19 '17 at 11:58

2 Answers2

1

A delegate is a common design pattern used in Cocoa and CocoaTouch frameworks, where one class delegates responsibility for implementing some functionality to another. This follows a principle of separation of concerns, where the framework class implements generic functionality while a separate delegate instance implements the specific use case.

Delegate properties being weak is a recommendation to help avoid retain cycles.For explaination check @Bary Walk ans here. However, there are use cases where a strong reference is preferred, or even necessary. Apple uses this in NSURLConnection: An NSURLConnection instance can only be used once. After it finishes (either with failure or success), it releases the delegate, and since the delegate is readonly, it can't be (safely) reused.Check this previous SO ques for reference.

luckyShubhra
  • 2,731
  • 1
  • 12
  • 19
0

As far as my knowledge declaring a object weak it means you are not own that object, so assigning strong delegate to it won't work.

Mahendra
  • 8,448
  • 3
  • 33
  • 56