Firing events accross multiple viewcontrollers from a thread in the appdelegate

拜拜、爱过 提交于 2020-01-02 07:26:10

问题


I have an NSAutoreleasePool thread that is designed to pull information down from a web service, i have the web service code working nicely and i can trigger the thread to start in a view controller without any trouble, in fact its working quite nicely.

I want to:

  • move the thread instantiation to the appDelegate - easy!
  • have it run periodically and somehow tell the viewcontrollers under it (5 - 10) if new information is downloaded
  • have the capacity to manually execute the thread outside of the scheduler

I can fire up a method on the appdelegate using performSelectorOnMainThread but how i can get my child view controllers to "subscribe" to a method on the appdelegate?


回答1:


Using NSNotificationCenter you can post well, notifications :D That way without the appDelegate nowing the other classes the other classes can "subscribe" to the notifications they need.

Also, i would keep the thread alive, spawning a new thread everytime is costly, ofc only if it is spawned often. I would recommend using GCD ( iOS 4+ )




回答2:


Here's what you do:

From the class sending the message, post a notification like :

[[NSNotificationCenter defaultCenter] postNotificationName: @"YOUR_NOTIFICATION_NAME" object: anyobjectyouwanttosendalong(can be nil)];

In the view controllers where you want to be notified of the notification when posted:

In the viewDidLoad do:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(METHOD_YOU_WANT_TO_INVOKE_ON_NOTIFICATION_RECEIVED) name:@"YOUR_NOTIFICATION_NAME" object:sameasbefore/nil];

Important! Don't forget this in your viewDidUnload():

[[NSNotificationCenter defaultCenter] removeObserver:self name:@"YOUR_NOTIFICATION_NAME" object:sameasbefore/nil];

I'm not very sure about the object associated with notifications but you can look that up here

NOTE: When it's only one object notifying another one, you're better off using protocols :) But in this case since there are multiple view controllers listening, use notifications




回答3:


Use NSNotificationCenter to send events that your view controllers are observing?



来源:https://stackoverflow.com/questions/5784378/firing-events-accross-multiple-viewcontrollers-from-a-thread-in-the-appdelegate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!