类方法有自己的东西吗?

ian*_*675 13 metaprogramming objective-c

我试图在Obj-C中编写一个ActiveRecord-esque位代码,并遇到以下情况:我试图在基类中创建一个静态类变量,它获取继承类的名称并转换为表名使用复数和一些其他格式化操作.我知道对于一个类的实例,可以按照以下方式执行某些操作:

tableName = [[[self class] description] stringToTableName];
Run Code Online (Sandbox Code Playgroud)

但是,这需要使用一个self.可以沿着以下几行做点什么吗?

tableName = [[[inheriting_class class] description] stringToTableName];
Run Code Online (Sandbox Code Playgroud)

我只是不想为每个继承的类对象实例重新计算表名.我也更喜欢让这些代码用ruby风格的元编程自动生成表名.

Jes*_*der 21

好用[self class]!在Objective-C中调用类方法时,self将指示正在调用哪个类.例如:

#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;
}
Run Code Online (Sandbox Code Playgroud)

应该打印

A called!
B called!
Run Code Online (Sandbox Code Playgroud)

  • +1,虽然你可以做`self`而不是`[self class]`.在类方法中,`self`*是*`Class`. (12认同)
  • @ iand675,`id`非常好.您希望将其声明为特定类型的唯一原因是编译时检查; 但是类型是在运行时确定的,所以无论如何都不需要它! (2认同)