您的位置:首页 > 运维架构

runloop的基本使用

2015-11-27 22:24 459 查看
#import "ViewController.h"

@interface
ViewController ()

@property (weak,
nonatomic) IBOutlet
UIImageView *imageView;

@property (nonatomic,
strong) NSThread *thread;

@end

@implementation ViewController

- (IBAction)oneBtnClick:(id)sender {

    

  self.thread =   [[NSThread
alloc]initWithTarget:self
selector:@selector(operation1)
object:nil];

    [self.thread
start];

}

- (IBAction)twoBtnClick:(id)sender {

    

    [self
performSelector:@selector(operation2)
onThread:self.thread
withObject:nil
waitUntilDone:YES];

}

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

{

    //Runloop的自动释放池子

    /*

     第一次创建:启动的时候

     最后一次销毁:退出

     其他:

        当runloop即将进入休眠状态的时候会销毁,重新创建一个空的自动释放池

     */

    NSLog(@"---start0----");

    /*

    //添加在runloop的默认运行模式下面的

    [self.imageView performSelector:@selector(setImage:) withObject:[UIImage imageNamed:@"Snip20151127_133"] afterDelay:2.0 inModes:@[NSDefaultRunLoopMode,UITrackingRunLoopMode]];

     */

}

-(void)operation1

{

//    while (1) {

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

//    }

    

    //开启runloop

    //创建子线程对应的runloop

    NSRunLoop *runloop = [NSRunLoop
currentRunLoop];

    

//    [runloop addPort:[NSMachPort port] forMode:NSDefaultRunLoopMode];

   NSTimer *timer =  [NSTimer
timerWithTimeInterval:2.0
target:self
selector:@selector(test)
userInfo:nil
repeats:YES];

    [runloop addTimer:timer
forMode:NSDefaultRunLoopMode];

   
//默认是没有开启的,需要手动开启

    [runloop run];

    

    //runloop要运行起来,mode里面至少要有一个source或者是timer

    

    NSLog(@"---end----");

}

-(void)operation2

{

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

}

-(void)test

{

    NSLog(@"---test---");

}

@end
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: