懒加载
声明属性
@property (nonatomic,strong) NSArray * name;
重写get方法
-(NSArray *)name{
if (!_name) {
_name = @[@"AAA",@"BBB"];
}
return _name;
}
Swift
lazy var name : String = {
return "abc"
}()
单例的创建方式
方式一:创建单例工厂方法(重写alloc完善)
声明全局静态变量
static Student * _student = nil;
创建单例类方法(如果不调用类方法,使用alloc init方法使用则不是单例)
+(instancetype)sharedStudent{
if (!_student) {
_student = [[Student alloc]init];
}
return _student;
}
方式二:GCD
声明全局静态变量
static Student * _student = nil;
创建dispatch_once只执行一次线程(如果不调用类方法,使用alloc init方法使用则不是单例)
+ (Student *)shareStudent {
static dispatch_once_t dispatch_once_token;
dispatch_once(&dispatch_once_token, ^{
_student = [[Student alloc]init];
});
return _student;
}
注意:方式一、方式二完善
重写alloc方法完善
+(instancetype)alloc{
//父类的alloc方法
if (!_student) {
_student = [super alloc];
}
return _student;
}
Swift
static let sharedInstance = NetworkUtils()
private override init() {}
网友评论