类方法是否有类似于self的东西? [英] Is there something like self for class methods?
问题描述
我试图在Obj-C中编写类似ActiveRecord的代码,并遇到以下情况:我试图在基类中创建一个静态类变量,该变量获取继承类的名称并转换为表名称具有复数形式和其他一些格式设置操作.我知道,对于一个类的实例,可以按照以下方式做一些事情:
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:
tableName = [[[self class] description] stringToTableName];
但是,这需要使用self
.可以按照以下几行做些什么吗?
However, this requires one to use self
. Is it possible to do something along following lines?
tableName = [[[inheriting_class class] description] stringToTableName];
我只希望不为继承的类对象的每个实例重新计算表名.我还希望使用这段代码使用ruby风格的元编程来自动生成表名.
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.
推荐答案
只需使用[self class]
!当您在Objective-C中调用类方法时,self
将指示正在调用哪个类.例如:
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;
}
应打印
A called!
B called!
这篇关于类方法是否有类似于self的东西?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!