Let's say I have class A and class B. In class A I create an instance of class B. Class B has delegate methods that, when called, I want to call instance methods in class A. Is there a way to pass a reference to class A when instantiating class B?
3 Answers
You can use a delegate to return information to the first Class
Class B.h
@protocol delegateB <NSObject> -(void)doSomething:(NSString *)data; @end @interface ClassB : UIViewController @property(nonatomic, assign) id<delegateB> delegate; @end Class B.m
@synthesize delegate = _delegate; - (void)viewDidLoad { [_delegate doSomething:@"String to send"]; } In the class A:
Class A.h
@interface ClassA : UIViewController -(void)doSomething:(NSString *)data; @end Class A.m
When you instance the class, you need to assign self:
ClassB *cb = [[ClassB alloc] init]; cb.delegate = self; To use the function:
-(void)doSomething:(NSString *)data{ //do something whit the data } Add a property of type A to B and assign self to it after initialising. You could also pass self as an argument to the delegate method you mentioned. Actually this is common practice in cocoa (look at UITableViewDelegate)
1 Comment
You can use type Class to pass a reference to a class. For class A use [A class] to get the referenece. But note that with a general class reference you won't be able to simply write [aClassRef aClassMethod], because Class instancce can reference any class (so the compiler don't know if particular method is supported or not).
The actual solution should be closer to what Julian suggests, but maybe this note will be useful in some way too.
+ (void)method;) then you don't need a reference. You need the reference if they are instance methods (e.g.- (void)method;).