I’d like my controller to subscribe to notifications from view. However, before doing that, I’d like to confirm if it is OK for a view to know the instance of its controller?
Let me offer you a more specific example of what I have in mind.
My controller creates the view and informs it that it is its controller
self.gameView = [[GameView alloc] initWithController:self];
Once done, it subscribes for notifications from this view
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(saySomething:)
name:@"SaySomethingClever" object:nil];
Meanwhile the view does its thing, but when the right time comes, it posts a notification
[[NSNotificationCenter defaultCenter] postNotificationName:
@"SaySomethingClever" object:gvc];
In order for it to do it, the view needs to know the recipient of the notification (gvc).
I’d like to use this opportunity and as you whether the following is ok:
When initWithController is called, the view
-(id) initWithController: (GameViewController* )g {
gvc = g;
return [self initWithFrame:CGRectMake(0, 0, 480, 300)];
}
where initWithFrame:CGRectMake is a private method that handles specific view stuff.
Everything works fine, however, i wonder whether this approach is morally acceptable
It’s not strictly a problem if the view has a reference to its controller, but it looks like your real problem is a misunderstanding of the notification posting method.
The
objectargument isn’t the receiver. Indeed, if it were — if the poster of a notification had to know the object that was going to get the notification — that would defeat the entire purpose of the notification. You could just call the appropriate method! The point of notifications is that the poster doesn’t need to know the other objects which are listening.The
objectargument is actually used by the receiver to distinguish which notifications it should care about. Most frequently, the argument is the poster itself:but it can in fact be any object.
When registering for notifications, you can specify a particular instance whose notifications you’re interested in. This is the
objectargument toaddObserver:...The notification center will then only pass on those notifications whose name and object match what was specified.Even if you pass
nilfor theobjectinaddObserver:..., you can check the object of a received notification and only act if the poster was one that you are interested in.For example, there might be several windows in you application, and you may be interested in knowing when one of them is resized, but you don’t care what happens to the rest of them. You would pass just that window instance as the
objectforaddObserver:...To sum up, your view in this case doesn’t need that reference to its controller in order to for the controller to receive notifications posted by the view.
See also: “Posting Notifications”