在viewDidLoad中写入如下代码:
- (void)viewDidLoad
{
[super viewDidLoad];
showLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 300, 40)];
[self.view addSubview:showLabel];
NSInteger (^myBlock)(NSInteger) = ^(NSInteger age) {
showLabel.text = [NSString stringWithFormat:@"ange=%d", age];
NSLog(@"your age is %d", age);
return age*2;
};
NSLog(@"block called. result=%d", myBlock(32));
UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
btn.frame = CGRectMake(10, 100, 300, 40);
[self.view addSubview:btn];
[btn addTarget:self action:@selector(btnClicked:) forControlEvents:UIControlEventTouchUpInside];
}
运行, 我们会发现因为myBlock(32)被调用, 主界面上的showLabel被设置,由此可见block中是可以直接设置主界面的控件。接着看btnClicked:方法
- (void)btnClicked:(id)sender {
NSThread *aThread = [[NSThread alloc] initWithTarget:self selector:@selector(newThread:) object:nil];
[aThread start];
[aThread release];
}
- (void)newThread:(id)sender {
NSLog(@"nbew Thread, This is in new thread");
showLabel.text = [NSString stringWithFormat:@"Hello, from butn."];
}
然后我们再看一个重力加速度的代码,
self.motionManager = [[[CMMotionManager alloc] init] autorelease];
NSOperationQueue *queue = [[[NSOperationQueue alloc] init] autorelease];
motionManager.accelerometerUpdateInterval = 1.0/30.0;
[motionManager startAccelerometerUpdatesToQueue:queue withHandler:
^(CMAccelerometerData *accelerometerData, NSError *error) {
// 这里可以尝试进行
showLabel.text = [NSString stringWithFormat:@"from accelerometer."];
}];
当然上面的演示,并不表示我们就应该用子线程或者block来操作主界面的控件,仅仅是一个讨论而已, 正常的情况还是应该使用下面的方式来修改主线程UI的控件。
[self performSelectorOnMainThread:@selector(updateMainUI:) withObject:nil waitUntilDone:NO];