简体   繁体   English

是否可以在Objective-C中为类实例定义方法

[英]Is it possible to define method for a class instance in objective-c

In Ruby, I can define method for any object: 在Ruby中,我可以为任何对象定义方法:

jack = "jack"
def jack.say_hi
 puts "hi, I'm #{self}"
end
jack.say_hi

Is it possible to do the same thing in Objective-C? 在Objective-C中可以做同样的事情吗? How? 怎么样?

Simple answer: No. 简单答案:不可以。

There is no simple way to dynamically add a method to one particular instance of a class. 没有简单的方法可以将方法动态地添加到类的一个特定实例中。 If you drop both the requirement to do it dynamically and the to do it for only one instance, then you can use a category - which is a compile-time way of adding methods to an existing class, and hence all instances of that class. 如果您同时放弃了动态执行和仅针对一个实例执行的要求,则可以使用类别 -这是一种将方法添加到现有类以及该类的所有实例的编译时方法。

Complicated answer: Yes. 复杂的答案:是的。

In Objective-C the runtime provides a set of functions to do just about anything, you can create new classes on the fly, add methods to them, and change the class of an instance dynamically. 在Objective-C中,运行时提供了一组几乎可以执行任何操作的函数,您可以动态创建新类,向它们添加方法,并动态更改实例的类。 Using facilities such as these you could achieve the equivalent of your Ruby code. 使用这些工具,您可以实现与Ruby代码相当的功能。 The Objective-C key value observing (KVO) mechanism is built on these features. Objective-C 键值观察 (KVO)机制基于这些功能。

Using the runtime functions in this way is a non-trivial undertaking, best to accept that Objective-C and Ruby have different models in this area and to try to re-design what you want to do using the Objective-C language model. 以这种方式使用运行时功能并非易事,最好是接受Objective-C和Ruby在该领域具有不同的模型,并尝试重新设计使用Objective-C语言模型要做的事情。 However if you really want to try this lookup the "Objective-C Runtime Reference" and enjoy! 但是,如果您真的想尝试此查找“ Objective-C运行时参考”,请尽情享受!

HTH HTH

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM