views:

543

answers:

1

In the iphone app that I'm working on I use a custom class to manage network communication with the host. The class called protocolClass is an ivar in the appDelegate and alloc + init in the applicationDidFinishLaunching: method.

Now whenever the protocolClass receive data from the host, it calls protocolClassDidReceiveData: method in its delegate (which I set as the appDelegate). I need then to update the data in one of the customViewControllers in the UINavigatorController.

Should I just add a reference to the customViewController I need to update in the appDelegate? or is there some other more efficient method?

If I were to keep a reference to the customViewcontroller, what are the memory usage ramifications?

Thanks in advance.

+1  A: 

If I get you right, you want to update a view after an event occurs in some unrelated part of your program.

To reduce the number of dependencies in your code, I'd recommend to use an NSNotification instead of the more tightly coupled instance variable. Notifications are a Cocoa concept, which allows one part of your code to emit an event-like message that any number of listeners can register for.

In your case it would look like this:

AppDelegate header:

extern NSString* kDataReceived;

AppDelegate implementation:

NSString* kDataReceived = @"DataReceived";

- (void)protocolClassDidReceiveData:(NSData*)data {
    [[NSNotificationCenter defaultCenter] postNotificationName:kDataReceived
                                                        object:self
                                                      userInfo:data];
}

in the implementation of some interested listener class (e.g. your UIViewController):

// register for the notification somewhere
- (id)init
{
    self = [super init];
    if (self != nil) {
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(dataReceivedNotification:)
                                                     name:kDataReceived
                                                   object:nil];
    }
}

// unregister
- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

// receive the notification
- (void)dataReceivedNotification:(NSNotification*)notification
{
    NSData* data = [notification userInfo];
    // do something with data
}
Nikolai Ruhe
Thanks Nikolai, I'll check notificationCenter out then. Initially I was just worried about using notificationCenter meaning using up unnecessary system resources.
Ben
I think that would have been premature optimization. If you look at how many notifications are flying around from all the views and so, I don't think it would do any harm to post a notification after receiving data from a socket.
Nikolai Ruhe
Thanks Nikolai! I was googling event passing in the iphone and saw your post
ambertch