在iOS App中访问Singleton

时间:2014-09-07 19:09:33

标签: ios singleton reachability

这是一个关于单身人士的简单问题,我希望有人可以迅速为我解决问题。

我按照本教程创建了一个用于监控应用中网络状态的Singleton。

http://code.tutsplus.com/tutorials/ios-sdk-detecting-network-changes-with-reachability--mobile-18299

在我的AppDelegate.m中,我按如下方式实例化管理器:

[ReachabilityManager sharedManager];

如果我现在要检查此sharedManager,如何从我的应用程序中的viewControllers访问它?

这就是班级的样子:

#import "ReachabilityManager.h"
#import "Reachability.h"

@implementation ReachabilityManager

#pragma mark -
#pragma mark Default Manager
+ (ReachabilityManager *)sharedManager {
    static ReachabilityManager *_sharedManager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _sharedManager = [[self alloc] init];
    });

    return _sharedManager;
}

#pragma mark -
#pragma mark Memory Management
- (void)dealloc {
    // Stop Notifier
    if (_reachability) {
        [_reachability stopNotifier];
    }
}

#pragma mark -
#pragma mark Class Methods
+ (BOOL)isReachable {
    return [[[ReachabilityManager sharedManager] reachability] isReachable];
}

+ (BOOL)isUnreachable {
    return ![[[ReachabilityManager sharedManager] reachability] isReachable];
}

+ (BOOL)isReachableViaWWAN {
    return [[[ReachabilityManager sharedManager] reachability] isReachableViaWWAN];
}

+ (BOOL)isReachableViaWiFi {
    return [[[ReachabilityManager sharedManager] reachability] isReachableViaWiFi];
}

#pragma mark -
#pragma mark Private Initialization
- (id)init {
    self = [super init];

    if (self) {
        // Initialize Reachability
        self.reachability = [Reachability reachabilityWithHostname:@"www.google.com"];

        // Start Monitoring
        [self.reachability startNotifier];
    }

    return self;
}

@end

1 个答案:

答案 0 :(得分:1)

非常容易:

#import "ReachabilityManager.h"

// Maybe in viewDidLoad
ReachabilityManager *sharedManager = [ReachabilityManager sharedManager];
// do stuff with your sharedManager