2013年12月25日 星期三

在block中要使用self的正確方式

//在進去之前要把它設為weak,讓self消失時,block中的self也跟著消失
//在進之之後要把它設為strong,讓self在block執行時,不會自行消失
__weak typeof(self) weakSelf = self;
    [_bleManager setReadingValueCompletion:^(NSData *responseData) {
        __strong typeof(weakSelf) strongSelf = weakSelf;
        strongSelf.showResult.text = [NSString stringWithFormat:@"%@",responseData];
        [strongSelf.receivedData appendData:responseData];

    }];

//在swift中使用
weak let weakSelf = self
或者在closure開頭加上[weak self]
在closure裡就直接使用self?
例如
dispatch_async(dispatch_get_main_queue(), { [weak self] () -> Void in
            self?.chatMessageTableView.reloadData()

        })

沒有留言:

張貼留言