开发者

Objective-C Late Static Binding

I'm teaching myself Objective-C as a guilty pleasure, if you would. I have a self-proclaimed strong grasp of the Java language, so it's not a terribly difficult transition – it sure is fun though. But alas, my question!

I'm attempting to reproduce something that exists in PHP: Late Static开发者_运维知识库 Binding. In PHP, I can decorate a method call with "static::", which will dynamically bind that method to the caller at runtime. On the other hand, if the keyword "self::" is used, the binding is static and is associated with the class in which it resides, regardless of which child class calls it.

In Obj-C, I'm having difficulty reproducing this paradigm. I've asked my overlord, Google, how to late statically bind in Cocoa, but I don't think it's possible. It may be called something else, or it may require a very over-my-head workaround. Here's what I'm doing now:

Parent Class Method:

-(id) whoAmI {
 return ([self class]);
}

A child class, ChildClass, extends ParentClass and does not override instance method whoAmI.

NSLog(@"Calling from PARENT: %@", [parent whoAmI]);
NSLog(@"Calling from CHILD: %@", [child whoAmI]);

When I send the message to each of the class objects, dynamic binding does what it's supposed to do, and I get the following from NSLog():

2010-09-21 11:39:07.484 WhoAmI[4803:a0f] Calling from PARENT: Parent

2010-09-21 11:39:07.486 WhoAmI[4803:a0f] Calling from CHILD: Child

Ultimately, I want to learn – if possible – how to get Cocoa to stop dynamically binding so that the whoAmI method always returns the object in which it resides (always Parent). I also want it to be an instance method. How would I go about doing this?

-Sean


Actually Objective C has a powerful set of introspection features, and it is almost certainly possible to do what you want by referring to Apple's extensive Objective C Runtime documentation. This is a complete C API for accessing the inner workings of Objective C's object & class hierarchy.

If nothing else, by experimenting with this stuff you'll learn a lot about how the language works and it should help you in debugging difficult problems.


Change the method to incorporate the name of the Parent class (or the superclass):

-(id) whoAmI {
 return ([Parent class]);    //In this instance, Parent is the superclass
}

It just so happens that what I wished to create had to be brought about by statically binding my class message to the parent class itself: Parent.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜