Reusing methods in multiple classes
I've just implemented iAds in an app with several distinct UIViewControllers.
I have the delegate methods in each one for - (void)bannerViewDidLoadAd:(ADBannerView *)banner
and - (void)ba开发者_高级运维nnerView:(ADBannerView *)banner didFailToReceiveAdWithError:(NSError *)error
that show and hide the banner, along with a setup method that creates a banner during viewDidLoad.
I did this by getting everything working in the first UIViewController
and then copying the code to each of the other controllers, along with the ivar
declarations, properties, etc...
This can't be right. Every time I change one, I have to change them all. My question (finally!) is: Is there a way to write these methods once so that all classes have access to them?
Thanks!
i recommend creating a c function if subclassing does not make sense.
if this function accompanies other related functions, place it in a library with its relatives. if the list becomes long, a class may have been a better choice.
if this function is standalone and specific to one app/project, then just create a file which declares all of these odd bits (if they must be reused across multiple translations). if the file of bits is really large, there's likely a few design issues.
some people may recommend an objc category instance method. i generally avoid categories because the chance for error is unnecessarily high. C and C++ functions/types, are linked and easily stripped if they are not referenced. with a category, you don't link, and it and the symbols used in the method must not be stripped.
you could include this as an instance method for your singleton, if the two are conceptually (or physically) bound. otherwise, i recommend keeping them separate.
精彩评论