sebekish
sebekish

Reputation: 13

Sending 'self' to an object

I've got an IBOutlet and an IBAction connected to an AppController Class. When a button is clicked, it creates an instance of another class (CData) with a message to calculate a string. My problem was that I wanted the IBOutlet to be reachable from within the CData object.

I've solved it by including self in the message and created an update method to the IBOutlet in AppController.

- (IBAction)buttonClicked:(id)sender
{
CData *myData = [[CData alloc] init];
[myData calculateString:self];
[myData release];
}

And in calculateString I've done the following:

- (void)calculateString:(id)parent
{
   [parent updateTextLog:@"Print data..."];
}

It works like a charm. But my question is, as I'm trying to familiar myself to Obj-C and Cocoa, if this is a good way to solve the problem, or if there's another way?

It's just a proof of concept, as I very well know that I could have just let calculateString return a value.

Upvotes: 1

Views: 99

Answers (2)

windson
windson

Reputation: 667

If we were to follow the MVC architecture, and Cocoa Touch does, the model layer should be completely abstracted from view layer. In this case, giving your CData class access to an IBOutlet violates this principle - assuming that CData is a model-type class.
Like you said, one way of going about it is to return something from -calculateString. This may seem like more code but does not limit the reusability of your model class.

Upvotes: 1

Shaggy Frog
Shaggy Frog

Reputation: 27601

I would not solve the problem in this way.

If the CData class has to update the view in some way, then you should be doing it inside the IBAction method, or considering it as a Model class in the MVC pattern, and having it generate a NSNotifcation that the view can observe.

The former way is easiest:

- (IBAction)buttonClicked:(id)sender
{
    CData *myData = [[CData alloc] init];
    ReturnValueType someReturnValue = [myData calculateString:self];
    [someObject someMethod:someReturnValue];
    [myData release];
}

This reduces coupling since the CData (Model) class doesn't need to know about the existance of any Views or Controllers.

Upvotes: 3

Related Questions