开发者

Firing events accross multiple viewcontrollers from a thread in the appdelegate

开发者 https://www.devze.com 2023-03-01 03:48 出处:网络
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 w

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 开发者_JS百科controllers to "subscribe" to a method on the appdelegate?


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+ )


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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号