[Newbie] [Cocoa] MVC: How to let the model send messages back to the controller?

kabigon

Registered
I'm trying to write an application that (among other things) continually takes incoming text data from a network socket and writes it to an NSTextView window. (I'm using EDStream, part of the EDCommon framework, to handle the network operations.)

The basic logic of this part of the model looks more or less like this:
Code:
- (void) getText
{
   int i=0;

   while (i==0)
   {
      NS_DURING
      {
         lineIn = [myStream availableString];
           ~~somehow tell the controller to display lineIn in the View's main text window~~;
      }
      NS_HANDLER
         i=1; // break out when connection closes
      NS_ENDHANDLER
   }
}
Now, I could easily accomplish this by instantiating Controller and NetworkHandler (my model class) in Interface Builder, pointing them to each other, and saying [controller displayText:lineIn]. The thing is, I want to create NetworkHandler instances dynamically in order to have an unspecified number of sessions open at once.

I did figure out a way to do this that works, by saving a pointer "back to" the controller object within the model object:
Code:
// interface part of NetworkHandler.h

@interface NetworkHandler : NSObject
{
   id myController;
   
   NSString * sessionName;
   EDStream * myStream;
}
Code:
//excerpts from NetworkHandler.m

- (id)initPointingBackTo:(Controller *)theController
{
   [theController retain];
   myController = theController;
   return [self initWithSessionName:@""];
}

- (id)initWithSessionName:(NSString *)newSessionName
{
   [super init];
   [self setSessionName:newSessionName];
   return self;
}

...

{
   ...
   [myController displayText:lineIn]
   ...
}
... and then I instantiate NetworkHandler from Controller.m using:
Code:
session1 = [[NetworkHandler alloc] initPointingBackTo:self];
But I have to say, although this works, it doesn't "feel right" somehow. It just seems kludgey and, just for one example, prevents me from being able to create a standard init override for NetworkHandler.

Is there a better way to do this? Any advice would be greatly appreciated!
 
Back
Top