3

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?

Adam Purdie
  • 502
  • 5
  • 14

3 Answers3

3

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

Antwan van Houdt
  • 6,989
  • 1
  • 29
  • 52
3

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

Sid
  • 9,508
  • 5
  • 39
  • 60
1

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

Terry Wilcox
  • 9,010
  • 1
  • 34
  • 36