gpt4 book ai didi

ios - 如何正确设置 NSNotification 并发布?

转载 作者:行者123 更新时间:2023-12-01 18:17:23 24 4
gpt4 key购买 nike

我想为每个要使用的连接委托(delegate)创建一个单例可达性观察者,
但是我无法正确构建它,这是一些代码片段。

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 中做了一个 dealloc
- (void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}

但之前的通知仍然存在。

最佳答案

您正在调用方法 notificationTrigger但是您的测试类只有方法 notificationTrigger:带有冒号,即一个参数。

更改[myTestClass notificationTrigger];[myTestClass notificationTrigger:self];它应该可以工作。

如果您只希望通知显示一次,请在显示警报 View 后将自己移除为观察者,如下所示:

- (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];
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
}
}

关于ios - 如何正确设置 NSNotification 并发布?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20561822/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com