Pregunta

I've had working code for categories of UITextField and UITextField similar to the following on iOS5 and iOS6 devices. However, the UITextView category method does not appear to be called on an iOS7 device (an iPhone5S). The code is:

@interface UIView (CustomCategory)
-(void) someCategoryMethod;
@end

@implementation UIView (CustomCategory)
-(void) someCategoryMethod {
    NSLog(@"UIView category methods appear to work.");
}
@end

@interface UITextField (CustomCategory)
-(void) someCategoryMethod;
@end

@implementation UITextField (CustomCategory)
-(void) someCategoryMethod {
    [super someCategoryMethod];
    NSLog(@"UITextField category methods appear to work.");
}
@end

@interface UITextView (CustomCategory)
-(void) someCategoryMethod;
@end

@implementation UITextView (CustomCategory)
-(void) someCategoryMethod {
    [super someCategoryMethod];
    NSLog(@"UITextView category methods appear to work.");
}
@end

void testFunction() {
    UITextView* textView = [[[UITextView alloc] init] autorelease];
    [textView someCategoryMethod];

    UITextField* textField = [[[UITextField alloc] init] autorelease];
    [textField someCategoryMethod];
}

On an iOS5 device, this (testFunction) prints:

UIView category methods appear to work.
UITextView category methods appear to work.
UIView category methods appear to work.
UITextField category methods appear to work.

However, on an iOS7 device this prints:

UIView category methods appear to work.
UIView category methods appear to work.
UITextField category methods appear to work.

So the UIView category method is actually being called in preference to the UITextView category method, which appears to contradict this answer.

Could anyone clarify whether the above code should work as expected (i.e. as on iOS5 and iOS6)?

¿Fue útil?

Solución

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.

https://developer.apple.com/library/ios/documentation/cocoa/conceptual/ProgrammingWithObjectiveC/CustomizingExistingClasses/CustomizingExistingClasses.html

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top