开发者

Is there something like self for class methods?

I'm attempting to write an ActiveRecord-esque bit of code in Obj-C, and encountered the following situation: I'm trying to create a static class variable in a base class that gets the inheriting class's name and converts into the table name with pluralization and some other formatting operations. I know that for an instance of a class that one can do something along the lines of the following:

开发者_JS百科tableName = [[[self class] description] stringToTableName];

However, this requires one to use self. Is it possible to do something along following lines?

tableName = [[[inheriting_class class] description] stringToTableName];

I'd just prefer to not recalculate the table name for each instance of inherited class objects. I'd also prefer to have this bit of code autogenerate the table name with ruby-style metaprogramming.


Just use [self class]! When you call a class method in Objective-C, self will indicate which class is calling. For example:

#import <Foundation/Foundation.h>
#import <stdio.h>

@interface A: NSObject
+ (void)foo;
@end

@implementation A
+ (void)foo {
  printf("%s called!", [[[self class] description] UTF8String]);
}
@end

@interface B: A @end
@implementation B @end

int main()
{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    [A foo];
    [B foo];
    [pool release];
    return 0;
}

should print

A called!
B called!


How about using NSStringFromClass() (and NSStringFromSelector() if desired)?

NSLog(@"[%@ %@]", NSStringFromClass([self class]), NSStringFromSelector(_cmd));
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜