Block的使用注意

//網絡

//  ViewController.m併發

//  Block使用注意async

//atom

//  Created by renlei on 15/9/5.spa

//  Copyright (c) 2015 renlei. All rights reserved.隊列

//內存

 

#import "ViewController.h"開發

 

@interface ViewController ()get

 

//定義一個全局的隊列屬性,方便在任何方法中均可以使用這個Queueit

@property (nonatomic,strong) NSOperationQueue *queue;

 

@end

 

//UI控件 weak Strong 都沒有問題

//在開發中,基本會見到全部的UI控件都是用strong

//UI控件通常不要用懶加載的方式加載,UI控件與用戶是對應的,UI控件以外的,能用懶加載就用懶加載

 

@implementation ViewController

 

//懶加載

-(NSOperationQueue *)queue

{

    if (!_queue) {

        _queue = [[NSOperationQueue alloc]init];

        

        //設置最大併發數

        [_queue setMaxConcurrentOperationCount:6];

        

//        網絡因素

    }

    return _queue;

}

 

- (void)viewDidLoad {

    [super viewDidLoad];

   

}

 

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event

{

    //這裏直接在bloc 中使用self 會形成循環引用.block使用的注意點之一:循環引用

    //__weak type(self)wself = self;wself 就是self的弱引用寫法

    //GCD中的任務都是封裝在block,若是GCD中的block中出錯了,self ,會形成循環引用嗎?

    

//    dispatch_async(dispatch_get_main_queue(), ^{

//        

//        [self test];

//    });  會形成循環引用嗎> 不會形成循環引用,由於self對這個block 沒有強引用

    

    //建立操做

    __weak typeof(self) wself = self;

    NSBlockOperation *op = [NSBlockOperation

                            blockOperationWithBlock:^{

                                //block 中出現self.block self是強引用

                                

                                [wself test];

                                

                            }];

    

//    將操做添加到隊列中.

//    self.queue op 就是強引用

    [self.queue addOperation:op];

    

    

}

 

//接收到內存警告的時候,就會調用

-(void)didReceiveMemoryWarning

{

    [super didReceiveMemoryWarning];

    

    //取消操做,有兩個方法

//    1> 操做隊列取消全部的操做

    

    

//    取消全部的操做,對於取消的操做,沒法再次恢復

    [self.queue cancelAllOperations];

    

//    2> 單個從左能夠取消 NSOperation的方法

}

 

 

 

-(void)test1

 

{

//        NSOperation 高級操做:暫停/恢復

//    這兩個方法,通常用在與用戶交互的時候

    

//    暫停隊列中的全部操做

    [self.queue setSuspended:YES];

    

//    恢復隊列中的全部操做

    [self.queue setSuspended:NO];

    

    

}

 

-(void)test

{

    NSLog(@"=====%@",[NSThread currentThread]);

}

@end

相關文章
相關標籤/搜索