iOS - @synchronized(self)的用法
2017-10-18 16:22
459 查看
本文为转载,用于个人学习的笔记。为了尊重作者,贴上原文地址:http://www.cnblogs.com/linzhengbo/p/6126755.html
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;
}
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;
}
相关文章推荐
- iOS---------- @synchronized(self)的用法
- ios的self.用法
- IOS开发(49)之关于 self与内存相关的用法总结
- 关于@synchronized(self)的用法
- iOS 关键字 self 的用法
- IOS开发self.的用法总结
- 关于@synchronized(self)的用法
- IOS开发Objective-C基础之—self.用法
- iOS 线程安全之@synchronized的用法
- IOS开发self.的用法总结
- iOS开发中self的用法介绍
- @synchronized(self)的用法 小结
- 关于@synchronized(self)的用法
- ios中self的用法
- IOS关于self.用法的一些总结
- iOS @synchronized(self) 解释
- ios开发self的用法
- 关于@synchronized(self)的用法
- ios中self的用法
- ios的self.用法