Reputation: 12517
I have two controller classes A and B. A instantiates several of B. When the appropriate button is pressed in A, A instantiates a B and program flow is passed to B. At the end of B's run I want it to pass some data back to A. How is this possible?
To be more precise, I have an NSArray of Objects, which I would like to return to 'A' after B runs its last method...
Upvotes: 1
Views: 1225
Reputation: 3382
As Ray says, there are a number of ways, but the simplest is to pass an instance of A
as an argument to B
's initializer, and then just call A.whatever(...)
to pass the data back. It's probably easiest to define and use the whatever(...)
method as an informal protocol - you know it exists, and the two modules know it exists, but there's nothing specific in the code that requires it to exist.
If you want to have a way of declaring that B
will need an object to call back to and to specify what that object must be able to do, you could set up a formal protocol. This would say that you will need an object, not necessarily an A
, but any object, that conforms to MyBCallbackProtocol
, which you define as needing to have the one instance method of whatever(...)
. The formal protocol lets the compiler check that the object you pass in definitely supports the method call you want.
It's probably overkill for this situation - but if the communication between A
and B
becomes more complex, you might want to use it to be sure that you've implemented all the methods that you've decided you need. If A is changed, the protocol helps to ensure that B
will still be able to pass back its information.
NSNotificationCenter may be overkill as well if A
and B
are very specific to your app. It does, however, completely isolate B
while allowing others to get data from it; if B
is meant to be a reusable utility class, it's worth considering.
I would not pass in a reference to an ivar in A; this is getting B way too involved in A's business.
Upvotes: 1
Reputation: 1154
There is a few way to accomplish that, the easiest and fastest solution is to use NSNotificationCenter. With NSNotificationCenter you can subscribe and send custom notifications.
NSNotificationCenter: Receive
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didFinishParsing:) name:@"yourNoticationName" object:nil];
- (void)didFinishParsing:(NSNotification *)aNotification {...}
Send
NSDictionary *userInfo = [NSDictionary dictionaryWithObjectsAndKeys:@"some", @"optional", @"data", @":)" nil];
[[NSNotificationCenter defaultCenter] postNotificationName:@"yourNoticationName" object:nil userInfo:userInfo];
Upvotes: 0
Reputation: 12106
Lots of options:
Probably more, but these are the ones I use most often.
Upvotes: 3