开发者

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 t开发者_StackOverflow中文版his.

Thanks,


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


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


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.


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!


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜