我试图将 Objective-C 类别与 Java 和 Ruby 中的功能进行比较。请看看这些结论是否准确 -
Objective-C 类别向现有类添加新方法,即使您无权访问该类的源代码也是如此。 Java 没有类似的东西,但在 Ruby 中你可以“打开”任何类,包括像 String 这样的核心语言类。
class String
def my_new_method
"new test method"
end
end
"some string".my_new_method
=> "new test method"
类似地,在 Objective-C 中 - 您可以使用类别“重新打开”NSString 类。
#import "NSString+ForTest.h"
@implementation NSString (ForTest)
-(NSString*) myNewMethod {
return @"new test method";
}
@end
但是,我看到的一个区别是,在 Ruby 中,一旦在运行时中打开并修改了一个类,该类的所有后续使用都会受到影响,换句话说,这是一个系统范围的更改,而在 Objective-C 中只有导入此头文件(以及任何子类)的代码才会受到影响。 还有其他区别吗?
最佳答案
However, one difference I see is that, in Ruby, once a class is opened and modified within a runtime, ALL subsequent uses of that class are affected, in other words it is a system wide change, while in Objective-C only code that imports this header file (and any subclasses) are affected
不,在 Objective-C 中,使用类扩展编译的程序(或库)中的所有类都会受到影响,即使您的代码从未导入相关的头文件,因此该功能非常重要与 Ruby 类似。
关于java - Objective-C 类别与其他语言的功能比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18675910/