<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."];
}
然后我们再看一个重力加速度的代码,
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来操作主界面的控件,仅仅是一个讨论而已, 正常的情况还是应该使用下面的方式来修改主线程UI的控件。
[self performSelectorOnMainThread:@selector(updateMainUI:) withObject:nil waitUntilDone:NO];
- <iOS>关于子线程和block中操作主线程界面的控件讨论
- iOS多线程编程中,子线程如何访问和操作主线程UI中的视图控件(下载操作用子线程实现)
- 在子线程中操作主线程
- C# 子线程操作主窗体控件的解决方法
- C# 子线程操作主窗体控件的解决方法
- C#子线程操作主线程中的控件
- Java子线程中操作主线程Private级别数据
- 工作线程操作主界面控件引起死锁及解决
- 工作线程操作主界面控件引起死锁及解决
- 工作线程操作主界面控件引起死锁及解决
- C# 线程 委托 回调-操作主线程定义的控件
- C#中子线程操作主线程中窗体上控件的方法
- C# 在自定义线程中采用系统委托方式操作主窗体线程控件的方法
- C#中子线程操作主线程中窗体上控件的方法
- C#中子线程操作主线程中窗体上控件的方法
- C#中子线程操作主线程中窗体上控件的方法
- C#中子线程操作主线程中窗体上控件的方法
- C#新线程中操作主线程的控件 ,解…
- RecPermute Code
- HDU 4510-小Q系列故事——为什么时光不能倒流
- 在类和结构之间选择
- android中sqlite的使用(一)
- 基于音频指纹技术的微信“摇一摇搜歌”和QQ音乐“听歌识曲”
- <iOS>关于子线程和block中操作主线程界面的控件讨论
- C++类型转换
- jquery常用方法总结
- 少年派
- 1019 最大乘积连续子串
- Struts2原理详解
- Android SDK各个版本区别及如何选择
- 用jquery解析JSON数据的方法
- 1020 字符串编辑距离