目标C中具有相同功能名称的类别 [英] Categories with the same function name in Objective C

查看:131
本文介绍了目标C中具有相同功能名称的类别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果XCode项目有两个类别:

If an XCode project has two categories :

@implementation NSData (test1)
- (void) testData {
     NSLog(@"test data 1");
} 
@end

@implementation NSData (test2)
- (void) testData {
     NSLog(@"test data 2");
} 
@end

这个的预期输出是什么:

What is the expected output for this :

NSData* testData = [[NSData alloc] init];
[testData testData];

我得到的输出总是

#import "NSData+test1.h"

任何解释在这?有没有办法强制第一个类别?

Any explanations on this? Is there a way to force the first category?

这里的问题是,如果要导入两个具有同名类别的静态库的SDK,你怎么做?解决问题。我假设唯一的方法是让SDK创建者使用方法名称的前缀?

The problem here is that if you are importing two SDK's with static libraries that have categories with the same name, how do you get around the problem. I'm assuming the only way is to ask the SDK creator's to use a prefix for the method names?

推荐答案

行为是未定义,应该避免。以下是相关文档

The behavior is undefined and should be avoided. Here is the relevant documentation:


避免类别方法名称冲突



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

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.

如果类别中声明的方法的名称与方法$相同原始类中的b $ b,或同一
类(甚至是超类)中另一个类别中的方法,行为未定义为在运行时使用哪个
方法实现
。如果您使用具有自己类的类别,则不太可能成为
问题,但在使用类别向标准Cocoa或
Cocoa Touch类添加方法时可能会导致
问题。 / p>

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.

这篇关于目标C中具有相同功能名称的类别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆