我想爲每個連接代理使用一個單例可達性觀察者,但是我無法正確構建它,下面是一些代碼片段。如何正確設置NSNotification併發布?
MYReachability.m
static MYReachability *sharedInstance;
+ (MYReachability *)sharedInstance
{
if (sharedInstance == NULL) {
sharedInstance = [[MYReachability alloc] init];
}
return sharedInstance;
}
- (void)addReachabilityObserver
{
[[NSNotificationCenter defaultCenter] addObserver: self
selector: @selector(reachabilityChanged:)
name: kReachabilityChangedNotification
object: nil];
Reachability *reach = [Reachability reachabilityWithHostname: @"www.apple.com"];
[reach startNotifier];
}
- (void) reachabilityChanged: (NSNotification *)notification {
NSLog(@"notification: %@", notification);
Reachability *reach = [notification object];
if([reach isKindOfClass: [Reachability class]]) {
NetworkStatus status = [reach currentReachabilityStatus];
NSLog(@"reachability status: %u", status);
if (status == NotReachable) {
// Insert your code here
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error"
message:@"Cannot connect to server..."
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alert show];
}
}
}
在MYConnectionDelegate.m
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
if (error.code) {
// sending notification to viewController
[[MYReachability sharedInstance] addReachabilityObserver];
MYTestClass *myTestClass = [MYTestClass new];
[myTestClass notificationTrigger];
}
}
在MYTestClass.m
- (void)notificationTrigger
{
// All instances of TestClass will be notified
[[NSNotificationCenter defaultCenter]
postNotificationName:kReachabilityChangedNotification
object:self];
}
裏克,謝謝,這樣的作品,但這裏談到另一個問題, 每次調用都會生成多個通知到堆棧中... 我MYReachability.m
- (void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
取得了dealloc的,但以前的通知仍然存在。
你在說什麼棧?當您發送通知時,要執行的代碼只運行一次。你的意思是說有不止一個觀察員?順便說一下,你想通過將代碼放在dealloc中實現什麼?順便說一下,這不是你如何創建一個單身人士。 – Pochi
是的,alertView將顯示不止一次,就像它觸發數字的次數一樣多,好像之前的通知不會釋放。 – pqteru
查看我的更新回答。 – Rick