Explanation of how weakify and strongify work in ReactiveCocoa / libextobjc

nacross picture nacross · Feb 12, 2014 · Viewed 8.2k times · Source

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

Answer

Hugo picture Hugo · Mar 13, 2014

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.)