2

I need some advice about best practice of developing iOS app design

Here's what I'm dealing with: when iOS device looses internet connection (or doesn't have one and figuring that out) I want my app to go to some sort of offline mode, i.e. firing some event, sending some NSNotifications, m.b. showing some sort of alert etc. Accordingly, when iOS device gets it's connection back I want the oposite thing - move my app to some sort of online mode.

So, what I want is to have ability to access app's mode (i.e. to check whether app is online or offline) from within some of my ViewControllers. I'm thinking of two methods of storing app's state:

1) Have some AppDelegate's property and access it from anywhere via my AppDelegate. AFAIK, that's a wrong approach, because AppDelegate is not supposed to be used as global object for application, but for doing launch initialization and controlling application's state changes.

2) Store this information on Model level. But I have no idea what am I supposed to use on Model level for such purpose. I don't think using Core Data or NSUserDefaults is a good idea, because I don't want this property to be persistent, I need it only during current application running. And apart from Core Data and NSUserDefaults I don't actually know any other Model level techniques.

I don't include any code examples, because it's mostly a theoretical question.

4

3 回答 3

6

您可以使用单例模式并将变量存储为属性

例如

@interface GlobalData : NSObject

@property BOOL connectionAvailable;

+ (GlobalData *)sharedInstance;

@end

@implementation

+ (GlobalData *)sharedInstance {
    static GlobalData *sharedInstance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[GlobalData alloc] init];
    });
    return sharedInstance;
}

@end

// --- in some method
[GlobalData sharedInstance].connectionAvailable = /* connection state */;

// --- in some other method
BOOL connectionAvailable = [GlobalData sharedInstance].connectionAvailable;
于 2013-02-27T09:00:08.280 回答
1

第二种方法效果最好。您肯定不需要任何持久性来指示 Internet 连接的属性。一件好事是让你的模型成为一个单例类,它BOOL为互联网连接公开一个只读属性,你的视图控制器可以通过键值观察订阅它的变化。您的模型还可以在内部实现Reachability用于更新 Internet 连接状态的类。

于 2013-02-27T08:59:55.380 回答
1

我假设您使用的是 Apple 的 Reachability 类。http://developer.apple.com/library/ios/#samplecode/Reachability/Introduction/Intro.html

我在 Reachability 类上创建了一个类别来添加一个 sharedInstance 单例,它允许您检查 Internet 连接的状态。我在所有应用程序中都使用它。

这是你如何做单例:

如何实现与 ARC 兼容的 Objective-C 单例?

于 2013-02-27T09:07:26.210 回答