Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explanation of how weakify and strongify work in ReactiveCocoa / libextobjc

I understand that you should use @weakify @strongify to avoid retain cycles but I don't completely understand how they actually achieve this?

like image 518
nacross Avatar asked Feb 12 '14 01:02

nacross


2 Answers

code before preprocess:

@weakify(self)
[[self.searchText.rac_textSignal
  map:^id(NSString *text) {
      return [UIColor yellowColor];
  }]
 subscribeNext:^(UIColor *color) {
     @strongify(self)
     self.searchText.backgroundColor = color;
 }];

code after preprocess:

@autoreleasepool {} __attribute__((objc_ownership(weak))) __typeof__(self) self_weak_ = (self);
    [[self.searchText.rac_textSignal
      map:^id(NSString *text) {
          return [UIColor yellowColor];
      }]
     subscribeNext:^(UIColor *color) {
         @try {} @finally {}
 __attribute__((objc_ownership(strong))) __typeof__(self) self = self_weak_; // 1
 self.searchText.backgroundColor = color;  //2
     }];

1: define a new local variable “self”. this will shadow the global one.

2: so here we used the local variable “self”--self_weak_.

tips:

1.if we used self.xxx in block, we should place @strongify(self) over it.

2.don't forget use @weakify(self) to define the variable self_weak_.

(PS: I'm trying to learn English. I hope that you can understand what I'm saying.)

like image 103
Hugo Avatar answered Oct 20 '22 06:10

Hugo


When writing the question I stared harder at the macro definitions and I think it works as you might guess.

@weakify creates a new weakly referenced variable of the same type you pass in and assigns the original value to it

@strongify creates a variable that matches the original variable but it exists in the local scope and assigns to it the variable created by @weakify

like image 35
nacross Avatar answered Oct 20 '22 06:10

nacross