开发者

Access class methods from an instance in Objective-C

Given the following class,

@interface MyBaseClass : NSObject

-(void)printName
+(NSString*)printableName

@end

how can I call the class method +printableNa开发者_运维知识库me from within the instance method -printName without explicitly referring to MyBaseClass? [[self class] printableName] doesn't compile.

The idea is that subclasses will override +printableName so -printName should polymorphically invoke the appropriate +printableName for its class.


Declare MyBaseClass as

@interface MyBaseClass : NSObject

and your [[self class] name] should compile.

This compiles for me:

@interface MyBaseClass : NSObject
-(void)printName;
+(NSString*)printableName;
@end

@implementation MyBaseClass

-(void)printName
{
    [[self class] printableName];
}

+(NSString*)printableName {
    return @"hello";
}

@end 


Have you tried [object_getClass(this) printableName]?

(But you realize, of course, that you could also just create a version of

-(NSString*)printableName2 {
    return [MyBaseClass printableName]; 
}

in each of your classes and call [self printableName2]?)


From what you are describing, it should work. As you didn't offer your implementation, we won't be able to tell, what is wrong.

Based on this question, I wrote an example code for polymorphism in Objective-C.
It contains inheritance-based polymorphism, but also polymorphism based on formal and informal protocols. May you want check your code against it.

here an excerpt:

#import <Foundation/Foundation.h>

/*
 * 1.: Polymorphism via subclassing 
 */
@interface MyBaseClass : NSObject
-(void)printName;
+(NSString*)printableName;
@end

@implementation MyBaseClass

+(NSString *)printableName
{
    return NSStringFromClass(self);
}

-(void)printName
{
    NSLog(@"%@", [[self class] printableName]);
}

@end


@interface MySubBaseClass : MyBaseClass
@end

@implementation MySubBaseClass
@end

//...

int main (int argc, const char * argv[])
{

    /*
     * 1.: Polymorphism via subclassing. As seen in any Class-aware OO-language
     */
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    MyBaseClass *myBaseObject = [[MyBaseClass alloc] init];
    [myBaseObject printName];
    [myBaseObject release];

    MySubBaseClass *mySubBaseObject = [[MySubBaseClass alloc] init];
    [mySubBaseObject printName];
    [mySubBaseObject release];

    //...

    [pool drain];
    return 0;
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜