如果您希望将此特定方法放置在可以从整个应用程序访问和调用的位置,那么这只是一个设计决策。有多种方法可以实现这一目标。
在实现全局方法时,我喜欢使用单例范式。约翰华兹华斯在一篇简洁的博客文章中介绍了这一点:
http://www.johnwordsworth.com/2010/04/iphone-code-snippet-the-singleton-pattern/
这是一段快速的代码:
InternetConnectionChecker.h
#import <Foundation/Foundation.h>
@interface InternetConnectionChecker : NSObject
// Accessor for singelton instance of internet connection checker.
+ (InternetConnectionChecker *)sharedInternetConnectionChecker;
// Check to see whether we have a connection to the internet. Returns YES or NO.
- (BOOL)connected;
@end
InternetConnectionChecker.m
#import "InternetConnectionChecker.h"
@implementation InternetConnectionChecker
// Accessor for singelton instance of internet connection checker.
+ (InternetConnectionChecker *)sharedInternetConnectionChecker
{
static InternetConnectionChecker *sharedInternetConnectionChecker;
@synchronized(self)
{
if (!sharedInternetConnectionChecker) {
sharedInternetConnectionChecker = [[InternetConnectionChecker alloc] init];
}
}
return sharedInternetConnectionChecker;
}
// Check to see whether we have a connection to the internet. Returns YES or NO.
- (BOOL)connected
{
NSURL *scriptUrl = [NSURL URLWithString:@"http://www.google.com/m"];
NSData *data = [NSData dataWithContentsOfURL:scriptUrl];
if (data) {
NSLog(@"Device is connected to the internet");
return TRUE;
}
else {
NSLog(@"Device is not connected to the internet");
return FALSE;
}
}
@end
在我的示例中,我修改了您的方法以返回 true/false,以便您可以在 UI 中适当地处理调用该方法的结果,但如果您愿意,您可以继续显示 UIAlertView。
然后,您将按以下方式使用单例:
InternetConnectionChecker *checker = [InternetConnectionChecker sharedInternetConnectionChecker];
BOOL connected = [checker connected];