1

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?

1
  • 1
    If you are really talking about class methods (e.g. + (void)method;) then you don't need a reference. You need the reference if they are instance methods (e.g. - (void)method;). Commented Jan 13, 2016 at 20:52

3 Answers 3

1

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 } 
Sign up to request clarification or add additional context in comments.

2 Comments

Why isn't delegateA actually named delegateB? It's a protocol defined by ClassB and there should be no indication of ClassA associated there.
And don't forget to add @interface ClassA () <delegateB> ... @end to ClassA.m.
0

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

Thank you - It was actually just a lack of understanding of delegates that was my problem!
0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.