Question

I've a ViewController where I call a method from another class (TCP class), where I make a TCP connection to a server, that gives me a response. And I want to, when that TCP class, get's the response from the server, call another method from the ViewController.

Problems:

  1. I'm a noob.
  2. I'm initializing and allocating that first Viewcontroller on the TCP, and all my vars are reseted (something that I don't want).

So... What can I do to make it right? I just want to call a method from a different class, that is already allocated in memory.

Tks!

Was it helpful?

Solution

You could set up the ViewController as an observer to the TCP class. This is a link that explains an implementation of the observer pattern in Obj-C. (Very similar to what I use but in a nice write up.)

http://www.a-coding.com/2010/10/observer-pattern-in-objective-c.html

I usually like to separate the persistence layer from the interface as well. I use observers or KVO to notify my business logic and view controllers that something changed.

You can also send the information through the Notification Center that is provided if you prefer...

https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/nsnotificationcenter_Class/Reference/Reference.html

Basic Code Example:

@implementation ExampleViewController
//...
- (void)viewDidLoad
{
   [super viewDidLoad:animated];
   [TCPClass subscribeObserver:self];
}
- (void)viewDidUnload
{
   [super viewDidUnload:animated];
   [TCPClass unsubscribeObserver:self];
}
- (void)notifySuccess:(NSString*)input
{
   //Do whatever I needed to do on success
}
//...
@end

@implementation TCPClass
//...
//Call this function when your TCP class gets its callback saying its done
- (void)notifySuccess:(NSString*)input 
{    
    for( id<Observer> observer in [NSMutableArray arrayWithArray:observerList] )
    {
        [(NSObject*)observer performSelectorOnMainThread:@selector(notifySuccess:)   withObject:input waitUntilDone:YES];
    }
}
//maintain a list of classes that observe this one
- (void)subscribeObserver:(id<Observer>)input {
    @synchronized(observerList) 
    {
        if ([observerList indexOfObject:input] == NSNotFound) {
        [observerList addObject:input];
        }
    }
}

- (void)unsubscribeObserver:(id<Observer>)input {
    @synchronized(observerList) 
    {
        [observerList removeObject:input];
    }
}
//...
@end

//Observer.h
//all observers must inherit this interface
@protocol Observer
- (void)notifySuccess:(NSString*)input;
@end

Hope that helps!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top