美文网首页
iOS 单例

iOS 单例

作者: 广锅锅 | 来源:发表于2017-07-06 15:04 被阅读41次

在iOS开发中,我现在能想到的单例方式,有以下三种:

使用AppDelegate

每个程序都是一个UIApplication对象,整个应用程序都依赖这个对象,这个对象当然就是单例的了,而它的Delegate也就是单例的。

@interface AppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@property (nonatomic, strong) NSString *email;
@end

// 在需要使用单例的地方
AppDelegate *single = [UIApplication sharedApplication].delegate;
single.email;

使用单例对象

这是最普遍,最直观的做法了,使用AppDelegate是属于这一类的。

// 类声明
@interface GGSingleton : NSObject
@property (nonatomic, copy) NSString *email;
+ (GGSingleton *)single;
@end

// 类实现
@implementation GGSingleton
+ (GGSingleton *)single {
    static GGSingleton *_single;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        if (_single == nil) {
            _single = [[super allocWithZone:NULL] init];
        }
    });
    return _single;
}
+ (instancetype)allocWithZone:(struct _NSZone *)zone {
    return [GGSingleton single];
}
@end

// 在需要使用单例的地方
GGSingleton *single = [GGSingleton single];
single.email;

使用类对象

你有想过,其实程序中的每一个类,它也是一个对象吗?并且它是单例的。

@interface GGSingleton : NSObject
+ (NSString *)email;
+ (void)setEmail:(NSString *)email;
@end

@implementation GGSingleton
static NSString *_email;
+ (NSString *)email {
    return _email;
}
+ (void)setEmail:(NSString *)email {
    _email = email;
}
@end

// 在需要使用单例的地方
[GGSingleton email];

这样做有方便的地方:不需要自己去创建对象、去写获取单例的方法。获取属性时直接类方法调用也就可以拿到数据了。
但是也有麻烦的地方:单例的属性的getter、setter必须要自己去手动声明,且必须要自己去手动实现。


这三种方法用哪种好呢。。我也不知道。。

相关文章

网友评论

      本文标题:iOS 单例

      本文链接:https://www.haomeiwen.com/subject/jwmhhxtx.html