答案:
@protected —Methods defined in the class and any subclasses can directly access the instance variables that follow.This is the default case.
该类和所有的子类中的方法可以直接访问这样的变量,这是默认的。
@private —Methods defined in the class can directly access the instance variables that follow, but subclasses cannot.
该类中的方法可以访问这样的变量,子类不可以。
@public —Methods defined in the class and any other classes or modules can di- rectly access the instance variables that follow.
除了自己和子类中的方法外,也可以被其他类或者其他模块中的方法所访问。开放性最大。
@package —For 64-bit images, the instance variable can be accessed anywhere within the image that implements the class.
对于64位图像,这样的成员变量可以在实现这个类的图像中随意访问。
第一种,使用@synchronized(self)
static LocationController *sharedInstance;
+ (LocationController *)sharedInstance {
@synchronized(self) {
if (!sharedInstance)
sharedInstance=[[LocationController alloc] init];
}
return sharedInstance;
}
@synchronized
作用:创建了一个互斥锁,它的作用和其他语言中的互斥锁作用一样
解释:这个是Objective-C中的一个锁定令牌,方便一个对象在同一时间内被其他线程访问,起到了线程保护的作用
使用范围:一般在单例模式或者操作类的static变量的时候使用,即共用的变量的时候
外延:这个令牌隐式的包含了异常处理,如果你不想使用的话,就使用锁吧
第二种,使用GCD
static LocationController *sharedInstance;
+ (LocationController *)sharedInstance {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
if (!sharedInstance)
sharedInstance = [[self alloc] init];
});
return sharedInstance;
}
通过Grand Central Dispatch系统,无论你何时需要在后台运行某个事务,你仅仅需要调用一下dispatch_async,然后传需要执行的事务代码给它即可。
其实,Grand Central Dispatch隐藏了很多后台处理细节如锁和同步机制,并且它会根据情况创建一个新线程或使用已有的线程。
当你调用dispatch_async,你通过一个dispatch队列,在这个队列上存有很多block,先进先出,依次执行。
这个队列可以使用dispatch_create自己创建,也可以调用主线程队列dispatch_get_main_queue。这里建立的队列名称是onceToken。
第三种,使用NSOperationQueue
IOS2.0之后,ios又对Grand Central Dispatch做了封装,产生了一个新的类NSOperationQueue。
因此,使用NSOperationQueue就是使用Grand Central Dispatch,NSOperationQueue仅仅是建立在Grand Central Dispatch上一些简单的API。
static LocationController *sharedInstance;
+ (LocationController *)sharedInstance {
NSOperationQueue *onceToken=[[NSOperationQueue alloc] init];
[onceToken addOperationWithBlock:^(){
if (!sharedInstance)
sharedInstance = [[self alloc] init];
});
return sharedInstance;
}];
}
5线程同步和异步的区别?IOS中如何实现多线程的同步?
线程同步与异步区别
线程同步是多个线程同时访问同一资源,等待资源访问结束,浪费时间,效率低 线程异步:访问资源时在空闲等待时同时访问其他资源,实现多线程机制
异步处理就是,你现在问我问题,我可以不回答你,等我用时间了再处理你这个问题.同步不就反之了,同步信息被立即处理 -- 直到信息处理完成才返回消息句柄;异步信息收到后将在后台处理一段时间 -- 而早在信息处理结束前就返回消息句柄