开发者

How safe are Objective-C categories?

Objective-C categories are extremely useful, but there are some problems with this power. These come in basically two forms which I know of:

  • Two categories attempting to add the same convenience method. In this case, it is undefined which one is used. If you are careful - not adding too many methods or using particularly common method names - the first problem should almost never be an issue.
  • New methods being added to a class by a writer that clash with a category. In this case the category overrides the class method. Since the class may not be under my control, I am more worried about this problem.

Backporting changes should be fairly safe, but implementing interfaces or adding convenience methods seem more dangerous. I know that Cocoa seems to use it for convenience methods quite a lot, but then again the base class is under there control. I think maybe they are just using the categories 开发者_如何学Goto reduce dependencies - so a String class can have convenience methods for working in Cocoa, but if you don't use Cocoa, it isn't pulled in.

So, how safe are categories/what guidelines are there for keeping them safe?


Usually, when extending code not under your control (e.g. Foundation), it's traditional to use a prefix or suffix on the method name to avoid these sorts of collisions.

Example from Peter Hosey's perform on main thread category:

@interface NSObject (PRHPerformOnMainThread)
- (id) performOnMainThread_PRH;
@end

It's not the most beautiful solution, but if you're worried about fragility it's a good idea.


I found the Google Objective-C Style Guide useful and it includes a convention to help avoid the collisions you mention.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜