@synchronized(self)的用法 小結


@synchronized() 的作用是創建一個互斥鎖,保證在同一時間內沒有其它線程對self對象進行修改,起到線程的保護作用, 一般在公用變量的時候使用,如單例模式或者操作類的static變量中使用。

 
例一://單例的實現
 
Student.h
 
#import <Foundation/Foundation.h>
@interface Student : NSObject<NSCopying,NSMutableCopying>
@property(nonatomic,copy)NSString *name;
//1、在h文件中聲明一個類方法,用於初始化實例
+(id)shareStudent;
@end
 
Student.m
 
#import "Student.h"
//2、在.m文件中首先聲明一個static修飾的對象,此對象此時是一個空指針
static Student *stu = nil;
@implementation Student
//3、實現.h中聲明的類方法
+(id)shareStudent{
    //避免多線程操作帶來的弊端  (互斥鎖)
    @synchronized(self){
        if (stu == nil) {
            stu = [[Student alloc]init];
        }
        return stu;
    }
}
//4、避免alloc產生新對象,所以要重寫allocWithZone方法
+(instancetype)allocWithZone:(struct _NSZone *)zone{
    if (stu == nil) {
        stu = [super allocWithZone:zone];
    }
    return stu;
}
//5、未了避免拷貝產生新對象,我們需要重寫copyWithZone以及mutablecopyWithZone方法
-(id)copyWithZone:(NSZone *)zone{
    return stu;
}
-(id)mutableCopyWithZone:(NSZone *)zone{
    return stu;
}
@end
 
例二://操作類的實現

# import "NetworkManager.h"

 

static NetworkManager *network = nil;

 

@implementation NetworkManager

 

+ (NetworkManager *)getNetworkInstance{

@synchronized(self){

if (nil == network){

network = [[NetworkManager alloc] init];

{

}

return network;

}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM