今天讲category方法的名称冲突以及解决办法
Avoid Category Method Name Clashes
Because the methods declared in a category are added to an existing class, you need to be very careful about method names.
If the name of a method declared in a category is the same as a method in the original class, or a method in another category on the same class (or even a superclass), the behavior is undefined as to which method implementation is used at runtime. This is less
likely to be an issue if you’re using categories with your own classes, but can cause problems when using categories to add methods to standard Cocoa or Cocoa Touch classes.
An application that works with a remote web service, for example, might need an easy way to encode a string of characters using Base64 encoding. It would make sense to define a category on NSString to add an instance method to return a Base64-encoded version
of a string, so you might add a convenience method called base64EncodedString.
A problem arises if you link to another framework that also happens to define its own category on NSString, including its own method called base64EncodedString. At runtime, only one of the method implementations will “win” and be added to NSString, but which
one is undefined.
Another problem can arise if you add convenience methods to Cocoa or Cocoa Touch classes that are then added to the original classes in later releases. The NSSortDescriptor class, for example, which describes how a collection of objects should be ordered, has
always had an initWithKey:ascending: initialization method, but didn’t offer a corresponding class factory method under early OS X and iOS versions.
By convention, the class factory method should be called sortDescriptorWithKey:ascending:, so you might have chosen to add a category on NSSortDescriptor to provide this method for convenience. This would have worked as you’d expect under older versions of
OS X and iOS, but with the release of Mac OS X version 10.6 and iOS 4.0, a sortDescriptorWithKey:ascending: method was added to the original NSSortDescriptor class, meaning you’d now end up with a naming clash when your application was run on these or later
platforms.
In order to avoid undefined behavior, it’s best practice to add a prefix to method names in categories on framework classes, just like you should add a prefix to the names of your own classes. You might choose to use the same three letters you use for your
class prefixes, but lowercase to follow the usual convention for method names, then an underscore, before the rest of the method name. For the NSSortDescriptor example, your own category might look like this:
@interface NSSortDescriptor (XYZAdditions)
+ (id)xyz_sortDescriptorWithKey:(NSString *)key ascending:(BOOL)ascending;
@end
This means you can be sure that your method will be used at runtime. The ambiguity is removed because your code now looks like this:
NSSortDescriptor *descriptor =
[NSSortDescriptor xyz_sortDescriptorWithKey:@"name" ascending:YES];