【问题标题】:UITextView category inheritance fails to work as expected on iOS7 deviceUITextView 类别继承在 iOS7 设备上无法按预期工作
【发布时间】:2013-11-21 04:15:21
【问题描述】:

我在 iOS5 和 iOS6 设备上为 UITextField 和 UITextField 类别提供了类似于以下内容的工作代码。但是,在 iOS7 设备(iPhone5S)上似乎没有调用 UITextView 类别方法。代码是:

@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];
}

在 iOS5 设备上,此 (testFunction) 打印:

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

但是,在 iOS7 设备上会打印:

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

所以 UIView 类别方法实际上是优先于 UITextView 类别方法被调用的,这似乎与this answer 矛盾。

谁能澄清上述代码是否应该按预期工作(即在 iOS5 和 iOS6 上)?

【问题讨论】:

  • 您的示例代码不会重现您在 iOS7 下的问题中列出的输出。它按预期输出继承。
  • @FruityGeek:代码肯定会在我正在使用的 iPhone5S 上产生规定的输出(因此我假设它适用于 iOS7,因为我没有任何其他 iOS7要测试的设备)。

标签: ios objective-c uitextview objective-c-category


【解决方案1】:

避免类别方法名称冲突

因为在类别中声明的方法被添加到现有的 类,你需要非常小心方法名称。

如果类别中声明的方法名称与方法相同 在原来的类中,或者另一个类中的方法就同 类(甚至是超类),行为是未定义 运行时使用哪种方法实现。

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

【讨论】:

    猜你喜欢
    • 2019-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-17
    • 1970-01-01
    • 2022-12-13
    • 1970-01-01
    相关资源
    最近更新 更多