java - Objective-C 类别与其他语言的功能比较

标签 java objective-c ruby objective-c-category

我试图将 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/

相关文章:

java - JDeveloper 中的集成 WebLogic Server 运行问题

iphone - 我怎样才能拥有包含两个以上 'if' 语句的 IBAction?

ruby - 如何为 Rspec 标准输出匹配器提供多个字符串?

ruby-on-rails - 使用回形针通过 Activeadmin Rails 上传文件

java - JTextField 未按照 swing 的预期将值从文本字段传递到对象字段

java - 这行java代码有什么问题吗?

java - Perf4j 私有(private)方法的 @profiled 注释

ios - 如何使用 PHPhotoLibrary 将图像导出到手机图库

html - 如何在 UITextView 中加载 HTML?

ruby - 这里的方括号是什么意思?