문제

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top