Tim Purple
Tim Purple

Reputation: 100

How do I call a class function from within an object within the class?

Basically, I want to call a function of a main class within a subclass that the main class holds a pointer to.
I know I can just get the main class to initiate the subclass and attach the function to it. But I do not want that, I want the subclass to initiate itself with its init function.
Is there any way I can call doSomething from someClass?
Some basic code to show what I want:
In MainViewController.h:

@class SomeClass;

@interface MainViewController : UIViewController {
        SomeObject *someInformation;
        SomeClass *someInstance;
}
@property (nonatomic, strong) SomeClass *someInstance;

-(void)doSomething:(id)sender;
@end

In MainViewController.m:

@implementation MainViewController
@synthesize someInstance;
-(void)doSomething:(id)sender {
    //do something to someInformation
}
@end

In SomeClass.h:

@interface SomeClass : NSObject {
    UIStuff *outstuff;
}
@property (strong, nonatomic) UIStuff *outstuff;
-(void)somethingHappened:(id)sender;
@end

In SomeClass.m

@implementation SomeClass
@synthesize outStuff;
-(IBAction)somethingHappened:(id)sender {
    //call doSomething to the main class that points to this class
}
@end

Upvotes: 0

Views: 145

Answers (1)

Coleman S
Coleman S

Reputation: 498

Your terminology is shaky. Classes do not "hold" other classes. In your case, instances of class MainViewController have pointers to objects of class SomeClass. I am not being pedantic; poor terminology such as this casts doubt on one's understanding of underlying and important concepts.

That said, SomeClass objects need a reference to a MainViewController object if you want a SomeClass object to be able to send a message to a MainViewController instance. From the code you have posted, no such reference exists. You either need to expand the SomeClass interface to store an explicit reference to a MainViewController object, or you can employ something slightly more indirect (at least conceptually) via delegation. However, because you have not provided case-specific information, our solutions will be formed lacking detail-derived insight.

Upvotes: 2

Related Questions