Reputation: 4594
In Ruby, I can define method for any object:
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? How?
Upvotes: 0
Views: 93
Reputation: 53000
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. Using facilities such as these you could achieve the equivalent of your Ruby code. The Objective-C key value observing (KVO) mechanism is built on these features.
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. However if you really want to try this lookup the "Objective-C Runtime Reference" and enjoy!
HTH
Upvotes: 5