ios34---GDC,dispatch_once

//
//  ViewController.m
//  09-掌握-GCD經常使用函數
//
//  Created by xiaomage on 16/2/18.
//  Copyright © 2016年 小碼哥. All rights reserved.
//

#import "ViewController.h"
#import "XMGPerson.h"

@interface ViewController ()

@end

@implementation ViewController

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
//    [self once];
    
    XMGPerson *p1 = [[XMGPerson alloc]init];
    XMGPerson *p2 = [[XMGPerson alloc]init];
    NSLog(@"%@---%@",p1.books,p2.books);
}

//延遲執行
-(void)delay
{
    NSLog(@"start-----");
    
    //1. 延遲執行的第一種方法
    //[self performSelector:@selector(task) withObject:nil afterDelay:2.0];
    
    //2.延遲執行的第二種方法
    //[NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(task) userInfo:nil repeats:YES];
    
    //3.GCD
//    dispatch_queue_t queue = dispatch_get_main_queue();
     dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
    /*
     第一個參數:DISPATCH_TIME_NOW 從如今開始計算時間
     第二個參數:延遲的時間 2.0 GCD時間單位:納秒
     第三個參數:隊列
     */
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), queue, ^{
        NSLog(@"GCD----%@",[NSThread currentThread]);
    });

}

//一次性代碼
//不能放在懶加載中的,應用場景:單例模式
-(void)once
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{  //整個項目生命週期只執行一次,屢次調用都不會執行屢次
        NSLog(@"---once----");
    });
}

-(void)task
{
    NSLog(@"task----%@",[NSThread currentThread]);
}
@end
//
//  XMGPerson.h
//  09-掌握-GCD經常使用函數
//
//  Created by xiaomage on 16/2/18.
//  Copyright © 2016年 小碼哥. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface XMGPerson : NSObject

@property (nonatomic, strong) NSArray *books;
@end
//
//  XMGPerson.m
//  09-掌握-GCD經常使用函數
//
//  Created by xiaomage on 16/2/18.
//  Copyright © 2016年 小碼哥. All rights reserved.
//

#import "XMGPerson.h"

@implementation XMGPerson

-(NSArray *)books
{
//    if (_books == nil) {
//        _books = @[@"1234",@"56789"];
//    }
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{  //只執行一次
        _books = @[@"1234",@"56789"];
    });
    return _books;
}
@end
相關文章
相關標籤/搜索