<iOS>关于子线程和block中操作主线程界面的控件讨论

来源:互联网 发布:阿里云 香港机房 被墙 编辑:程序博客网 时间:2024/05/16 14:16

在viewDidLoad中写入如下代码:

- (void)viewDidLoad

{

    [superviewDidLoad];


    showLabel = [[UILabelalloc] initWithFrame:CGRectMake(10,10, 300, 40)];

    [self.viewaddSubview:showLabel];

    

    NSInteger (^myBlock)(NSInteger) = ^(NSInteger age) {

        showLabel.text = [NSStringstringWithFormat:@"ange=%d", age];

        NSLog(@"your age is %d", age);

        return age*2;

    };

    

    NSLog(@"block called. result=%d", myBlock(32));

    

    UIButton *btn = [UIButtonbuttonWithType:UIButtonTypeRoundedRect];

    btn.frame =CGRectMake(10,100, 300, 40);

    [self.viewaddSubview:btn];

    [btn addTarget:selfaction:@selector(btnClicked:)forControlEvents:UIControlEventTouchUpInside];

}

运行, 我们会发现因为myBlock(32)被调用, 主界面上的showLabel被设置,由此可见block中是可以直接设置主界面的控件。

接着看btnClicked:方法

- (void)btnClicked:(id)sender {

    NSThread *aThread = [[NSThread alloc] initWithTarget:selfselector:@selector(newThread:)object:nil];

    [aThread start];

    [aThread release];

}

- (void)newThread:(id)sender {

    NSLog(@"nbew Thread, This is in new thread");

    showLabel.text = [NSStringstringWithFormat:@"Hello, from butn."];

}

运行,我们发现, 点按钮后,线程运行,并且showLabel的text被设置成"hello. from buton."由此可见,在子线程中是可以直接设置主界面上的控件的。

然后我们再看一个重力加速度的代码,

    self.motionManager = [[[CMMotionManageralloc] init]autorelease];

    NSOperationQueue *queue = [[[NSOperationQueuealloc] init] autorelease];

    motionManager.accelerometerUpdateInterval =1.0/30.0;

    [motionManagerstartAccelerometerUpdatesToQueue:queue withHandler:

     ^(CMAccelerometerData *accelerometerData,NSError *error) {

        // 这里可以尝试进行

          showLabel.text = [NSString stringWithFormat:@"from accelerometer."];

     }];

运行后,我们发现根本不能影响到主线程的控件,不知何故,估计是因为这个block和上面直接生成的 block有所不同,所以前面的block是可以设置,而在这里的accelerometer的handler中是不可设置的。

当然上面的演示,并不表示我们就应该用子线程或者block来操作主界面的控件,仅仅是一个讨论而已, 正常的情况还是应该使用下面的方式来修改主线程UI的控件。

   [self performSelectorOnMainThread:@selector(updateMainUI:) withObject:nil waitUntilDone:NO];


原创粉丝点击