gpt4 book ai didi

ios 注销观察者

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:13:55 25 4
gpt4 key购买 nike

我正在阅读 Apple 文档并看到:

Before an object that is observing notifications is deallocated, it must tell the notification center to stop sending it notifications. Otherwise, the next notification gets sent to a nonexistent object and the program crashes.

我试图让应用程序崩溃以更好地了解它的实际工作方式。

但是,即使我没有将这段代码放在SecondViewController dealloc 中,它仍然不会在发送通知后崩溃。我显然要添加观察者并从 secondViewController 返回并在 viewController 中推送通知。那么,如果这个程序不崩溃,为什么我们需要删除观察者?

[[NSNotificationCenter defaultCenter] removeObserver:self];

休息代码是:

// View Controller :

@implementation ViewController

- (void)viewDidLoad {
[super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. }

- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated. }

- (IBAction)go:(id)sender {
SecondViewController *secondViewController = [[SecondViewController alloc] initWithNibName:@"SecondViewController" bundle:nil];
[self presentViewController:secondViewController animated:NO completion:^{}];
[secondViewController release], secondViewController = nil; }

- (IBAction)push:(id)sender {
// All instances of TestClass will be notified
[[NSNotificationCenter defaultCenter] postNotificationName:@"TestNotification" object:self]; }

//第二 View Controller :

@implementation SecondViewController

- (void)dealloc {
[super dealloc]; }

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(receiveTestNotification:)
name:@"TestNotification"
object:nil];

}
return self; }

- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
}

- (void) receiveTestNotification:(NSNotification *) notification {
// [notification name] should always be @"TestNotification"
// unless you use this method for observation of other notifications
// as well.
NSLog (@"Successfully received the test notification!"); }

- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated. }

- (IBAction)back:(id)sender {
NSLog(@"");
[self dismissViewControllerAnimated:NO completion:^{}]; }

最佳答案

@Reno Jones 是对的。像这样删除观察者 - [[NSNotificationCenter defaultCenter] removeObserver:self name:@"TestNotification"object:nil];

还有一件事要添加到他的回答中,你应该在 - (void)dealloc{} 方法中移除观察者 - 这是在 self 被释放时调用的方法。

编辑:

我查看了代码,发现您没有使用 arc。还有一个问题,您为什么不在您的应用程序中使用 ARC?你有充分的理由用引用计数来强调自己吗,我不明白这一点?

其次,您能否在 viewDidLoad 方法中移动 addObserver 并看到它导致您的应用程序崩溃。

关于ios 注销观察者,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16611450/

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