|
马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有帐号?立即注册
x
如果同时支持iOS5和iOS4用宏判断下就可以当然也可以直接用assign)还有一点开始学习的时候肯定很疑惑内存管理是基于函数名称的比如带alloccopy的函数用了之后返回的对象一定要release1、简介:
1.1iOS有三种多线程编程的手艺,分离是:
1.、NSThread
2、CocoaNSOperation(iOS多线程编程之NSOperation和NSOperationQueue的利用)
3、GCD全称:GrandCentralDispatch(iOS多线程编程之GrandCentralDispatch(GCD)先容和利用)
这三种编程体例从上到下,笼统度条理是从低到高的,笼统度越高的利用越复杂,也是Apple最保举利用的。
这篇我们次要先容和利用NSThread,前面会持续2、3的解说和利用。
1.2三种体例的出缺点先容:
NSThread:
长处:NSThread比其他两个轻量级
弱点:必要本人办理线程的性命周期,线程同步。线程同步对数据的加锁会有必定的体系开支
NSThread完成的手艺有上面三种:
Technology
Description
Cocoathreads
CocoaimplementsthreadsusingtheNSThreadclass.CocoaalsoprovidesmethodsonNSObjectforspawningnewthreadsandexecutingcodeonalready-runningthreads.Formoreinformation,see“UsingNSThread”and“UsingNSObjecttoSpawnaThread.”
POSIXthreads
POSIXthreadsprovideaC-basedinterfaceforcreatingthreads.IfyouarenotwritingaCocoaapplication,thisisthebestchoiceforcreatingthreads.ThePOSIXinterfaceisrelativelysimpletouseandoffersampleflexibilityforconfiguringyourthreads.Formoreinformation,see“UsingPOSIXThreads”
MultiprocessingServices
MultiprocessingServicesisalegacyC-basedinterfaceusedbyapplicationstransitioningfromolderversionsofMacOS.ThistechnologyisavailableinOSXonlyandshouldbeavoidedforanynewdevelopment.Instead,youshouldusetheNSThreadclassorPOSIXthreads.Ifyouneedmoreinformationonthistechnology,seeMultiprocessingServicesProgrammingGuide.
一样平常利用cocoathread手艺。
Cocoaoperation
长处:不必要体贴线程办理,数据同步的事变,能够把精神放在本人必要实行的操纵上。
Cocoaoperation相干的类是NSOperation,NSOperationQueue。NSOperation是个笼统类,利用它必需用它的子类,能够完成它大概利用它界说好的两个子类:NSInvocationOperation和NSBlockOperation。创立NSOperation子类的对象,把对象增加到NSOperationQueue行列里实行。
GCD
GrandCentralDispatch(GCD)是Apple开辟的一个多核编程的办理办法。在iOS4.0入手下手以后才干利用。GCD是一个替换诸如NSThread,NSOperationQueue,NSInvocationOperation等手艺的很高效和壮大的手艺。如今的iOS体系都晋级到6了,以是不必忧虑该手艺不克不及利用。
先容完这三种多线程编程体例,我们这篇先先容NSThread的利用。
2、NSThread的利用
2.1NSThread有两种间接创立体例:
-(id)initWithTarget:(id)targetselector:(SEL)selectorobject:(id)argument
+(void)detachNewThreadSelector:(SEL)aSelectortoTarget:(id)aTargetwithObject:(id)anArgument
第一个是实例办法,第二个是类办法
- 1、[NSThreaddetachNewThreadSelector:@selector(doSomething:)toTarget:selfwithObject:nil];
- 2、NSThread*myThread=[[NSThreadalloc]initWithTarget:self
- selector:@selector(doSomething:)
- object:nil];
- [myThreadstart];
2.2参数的意义:
selector:线程实行的办法,这个selector只能有一个参数,并且不克不及有前往值。
target:selector动静发送的对象
argument:传输给target的独一参数,也能够是nil
第一种体例会间接创立线程而且入手下手运转线程,第二种体例是先创立线程对象,然后再运转线程操纵,在运转线程操纵前能够设置线程的优先级等线程信息
2.3PS:不显式创立线程的办法:
用NSObject的类办法performSelectorInBackground:withObject:创立一个线程:
[ObjperformSelectorInBackground:@selector(doSomething)withObject:nil];
2.4下载图片的例子:
2.4.1新建singeViewapp
新建项目,并在xib文件上安排一个imageView控件。按住control键拖到viewControll
er.h文件中创立imageViewIBOutlet
ViewController.m中完成:
- //
- //ViewController.m
- //NSThreadDemo
- //
- //Createdbyrongfzhon12-9-23.
- //Copyright(c)2012年rongfzh.Allrightsreserved.
- //
- #import"ViewController.h"
- #definekURL@"http://avatar.csdn.net/2/C/D/1_totogo2010.jpg"
- @interfaceViewController()
- @end
- @implementationViewController
- -(void)downloadImage:(NSString*)url{
- NSData*data=[[NSDataalloc]initWithContentsOfURL:[NSURLURLWithString:url]];
- UIImage*image=[[UIImagealloc]initWithData:data];
- if(image==nil){
- }else{
- [selfperformSelectorOnMainThread:@selector(updateUI:)withObject:imagewaitUntilDone:YES];
- }
- }
- -(void)updateUI:(UIImage*)image{
- self.imageView.image=image;
- }
- -(void)viewDidLoad
- {
- [superviewDidLoad];
- //[NSThreaddetachNewThreadSelector:@selector(downloadImage:)toTarget:selfwithObject:kURL];
- NSThread*thread=[[NSThreadalloc]initWithTarget:selfselector:@selector(downloadImage:)object:kURL];
- [threadstart];
- }
- -(void)didReceiveMemoryWarning
- {
- [superdidReceiveMemoryWarning];
- //Dispo搜索引擎优化fanyresourcesthatcanberecreated.
- }
- @end
2.4.2线程间通信
线程下载完图片后怎样关照主线程更新界面呢?
[selfperformSelectorOnMainThread:@selector(updateUI:)withObject:imagewaitUntilDone:YES];
performSelectorOnMainThread是NSObject的办法,除能够更新主线程的数据外,还能够更新其他线程的好比:
用:performSelector:onThread:withObject:waitUntilDone:
运转下载图片:
<br>
图片下载上去了。
2.3线程同步
我们演示一个典范的卖票的例子来说NSThread的线程同步:
.h
- #import<UIKit/UIKit.h>
- @classViewController;
- @interfaceAppDelegate:UIResponder<UIApplicationDelegate>
- {
- inttickets;
- intcount;
- NSThread*ticketsThreadone;
- NSThread*ticketsThreadtwo;
- NSCondition*ticketsCondition;
- NSLock*theLock;
- }
- @property(strong,nonatomic)UIWindow*window;
- @property(strong,nonatomic)ViewController*viewController;
- @end
- -(BOOL)application:(UIApplication*)applicationdidFinishLaunchingWithOptions:(NSDictionary*)launchOptions
- {
- tickets=100;
- count=0;
- theLock=[[NSLockalloc]init];
- //锁对象
- ticketsCondition=[[NSConditionalloc]init];
- ticketsThreadone=[[NSThreadalloc]initWithTarget:selfselector:@selector(run)object:nil];
- [ticketsThreadonesetName:@"Thread-1"];
- [ticketsThreadonestart];
- ticketsThreadtwo=[[NSThreadalloc]initWithTarget:selfselector:@selector(run)object:nil];
- [ticketsThreadtwosetName:@"Thread-2"];
- [ticketsThreadtwostart];
- self.window=[[UIWindowalloc]initWithFrame:[[UIScreenmainScreen]bounds]];
- //Overridepointforcustomizationafterapplicationlaunch.
- self.viewController=[[ViewControlleralloc]initWithNibName:@"ViewController"bundle:nil];
- self.window.rootViewController=self.viewController;
- [self.windowmakeKeyAndVisible];
- returnYES;
- }
- -(void)run{
- while(TRUE){
- //上锁
- //[ticketsConditionlock];
- [theLocklock];
- if(tickets>=0){
- [NSThreadsleepForTimeInterval:0.09];
- count=100-tickets;
- NSLog(@"以后票数是:%d,售出:%d,线程名:%@",tickets,count,[[NSThreadcurrentThread]name]);
- tickets--;
- }else{
- break;
- }
- [theLockunlock];
- //[ticketsConditionunlock];
- }
- }
假如没有线程同步的lock,卖票数多是-1.加上lock以后线程同步包管了数据的准确性。
下面例子我利用了两种锁,一种NSCondition,一种是:NSLock。NSCondition我已正文了。
iPhoneSDK安装,然后最基本的是你要熟悉C语言,再来你得学习开发iPhone所使用的Objective-C语言,接著是Cocoa。如果你是Mac平台开发的入门用户 |
|