iOS容易造成循环引用的三种场景

2016-06-16  本文已影响74人  走道牙的人

(1)计时器NSTimer

1 #import <Foundation/Foundation.h>
2 @interface Friend : NSObject
3 - (void)cleanTimer;
4 @end
 1 #import "Friend.h"
 2 @interface Friend ()
 3 {
 4     NSTimer *_timer;
 5 }
 6 @end
 7 
 8 @implementation Friend
 9 - (id)init
10 {
11     if (self = [super init]) {
12         _timer = [NSTimer scheduledTimerWithTimeInterval:1 
                       target:self selector:@selector(handleTimer:) 
                       userInfo:nil repeats:YES];
14     }
15     return  self;
16 }
17 
18 - (void)handleTimer:(id)sender
19 {
20     NSLog(@"%@ say: Hi!", [self class]);
21 }
22 - (void)cleanTimer
23 {
24     [_timer invalidate];
25     _timer = nil;
26 }
27 - (void)dealloc
28 {
29     [self cleanTimer];
30     NSLog(@"[Friend class] is dealloced");
31 }
1         Friend *f = [[Friend alloc] init];
2         dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 
            5*NSEC_PER_SEC), dispatch_get_main_queue(), ^{
3             [f release];
4         });
2015-03-18 18:00:35.300 WZLCodeLibrary[41422:3390529] Friend say: Hi!
2015-03-18 18:00:36.299 WZLCodeLibrary[41422:3390529] Friend say: Hi!
2015-03-18 18:00:37.300 WZLCodeLibrary[41422:3390529] Friend say: Hi!
2015-03-18 18:00:38.299 WZLCodeLibrary[41422:3390529] Friend say: Hi!
2015-03-18 18:00:39.299 WZLCodeLibrary[41422:3390529] Friend say: Hi!//运行了5次后没按照预想的停下来
2015-03-18 18:00:40.299 WZLCodeLibrary[41422:3390529] Friend say: Hi!
2015-03-18 18:00:41.300 WZLCodeLibrary[41422:3390529] Friend say: Hi!
2015-03-18 18:00:42.300 WZLCodeLibrary[41422:3390529] Friend say: Hi!
2015-03-18 18:00:43.299 WZLCodeLibrary[41422:3390529] Friend say: Hi!
2015-03-18 18:00:44.300 WZLCodeLibrary[41422:3390529] Friend say: Hi!//.......根本停不下来.....
Friend *f = [[Friend alloc] init];
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 
5*NSEC_PER_SEC), dispatch_get_main_queue(), ^{
    [f cleanTimer];
    [f release];
});

(2)block

#import "Friend.h"

@interface Friend ()
@property (nonatomic) NSArray *arr;
@end

@implementation Friend
- (id)init
{
    if (self = [super init]) {
         self.arr = @[@111, @222, @333];
        self.block = ^(NSString *name){
            NSLog(@"arr:%@", self.arr);
        };
    }
    return  self;
}
01.png 02.png
__weak typeof(self) weakSelf = self;
self.blkA = ^{
__strong typeof(weakSelf) strongSelf = weakSelf;//加一下强引用,避免weakSelf被释放掉
NSLog(@"%@", strongSelf->_xxView); //不会导致循环引用.
};
1          self.arr = @[@111, @222, @333];
2         __weak typeof(self) weakSelf=self;
3         self.block = ^(NSString *name){
4             NSLog(@"arr:%@", weakSelf.arr);
5         };

(3)委托delegate

上一篇 下一篇

猜你喜欢

热点阅读