UITableViewCell和UICollectionViewCell復(fù)用使用RAC的問題,解決復(fù)用cell中信號的辦法就是在cell里面創(chuàng)建的信號加上takeUntil:cell.rac_prepareForReuseSignal來讓cell在每次重用的時候都去
disposable創(chuàng)建的信號(解綁信號)
具體看代碼:
- (NSInteger)tableView:(nonnull UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return 1000;
}
- (UITableViewCell *)tableView:(nonnull UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"TableViewCell"];
@weakify(self);
[RACObserve(cell.textLabel, text) subscribeNext:^(id x) {
@strongify(self);
NSLog(@"%@", self);
}];
return cell;
}
我們看到這里的RACObserve創(chuàng)建的Signal和self之間已經(jīng)去掉了循環(huán)引用的問題,所以應(yīng)該是沒有什么問題的。但是結(jié)合之前我們對RACObserve的理解再仔細分析一下,這里的Signal只要self沒有被dealloc的話就不會被釋放。雖然每次UITableViewCell都會被重用,但是每次重用過程中創(chuàng)建的信號確實無法被disposable。那我們該怎么做呢?
- (NSInteger)tableView:(nonnull UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return 1000;
}
- (UITableViewCell *)tableView:(nonnull UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"TableViewCell"];
@weakify(self);
[[RACObserve(cell.textLabel, text) takeUntil:cell.rac_prepareForReuseSignal] subscribeNext:^(id x) {
@strongify(self);
NSLog(@"%@", self);
}];
return cell;
}
注意,我們在cell里面創(chuàng)建的信號加上takeUntil:cell.rac_prepareForReuseSignal,這個是讓cell在每次重用的時候都去disposable創(chuàng)建的信號。