Ashutosh
Ashutosh

Reputation: 5742

How to call a method of one obj c class into another obj c class

I have a class with methods which i want to use in another class and don't want to create those methods again. I know it's silly question but i have never done this.

Thanks,

Upvotes: 1

Views: 164

Answers (6)

user142019
user142019

Reputation:

You should be able to do this with the ObjC Runtime, but subclassing is a better option in my opinion.

Upvotes: 0

FreeAsInBeer
FreeAsInBeer

Reputation: 12979

As everyone else has stated, you have numerous options, but we can't determine the best one until you describe your objects and their structure in more detail.

Upvotes: 0

picciano
picciano

Reputation: 22701

There's not one right answer here. A lot depends on your specific situation and object model. A few different approaches you could take:

1) Create a super class that implements the methods you want to reuse. Each of your current classes that need this function could extend this new super class.

2) If the functionality is not integral to the class, you might want to create a "utility" class that could be called by each class that needs it.

3) In some situations, it may be appropriate to create a "Category" to extend the functionality of the class you are sub-classing.

In general, think about your object model and decide where that functionality belongs. If you find yourself copy-pasting a lot, it's a warning sign that your model might be a bit off. Good luck!

Upvotes: 1

Greg
Greg

Reputation: 33650

You could use inheritance to solve this problem. In AnotherClass's declaration (in the .h file), you would declare that it extends ParentClass:

@interface AnotherClass : ParentClass {
    // ...
}

// method declarations for methods that are new in AnotherClass
// methods from ParentClass would be inherited by AnotherClass

@end

Upvotes: 3

Caleb
Caleb

Reputation: 125007

Can you explain the relationship between the two classes? Could the new one be a subclass of the existing class? Two independent classes really can't share implementations -- one class can't borrow instance methods of another class unless there's an inheritance relationship between them.

Upvotes: 1

Simon Goldeen
Simon Goldeen

Reputation: 9080

Sounds like you should make the second class a subclass of the first class or make a common superclass for your two classes

Upvotes: 1

Related Questions