Is there something like self for class methods?

匿名 (未验证) 提交于 2019-12-03 01:49:02

问题:

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]; 

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.

回答1:

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

#import  #import   @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! 


回答2:

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

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


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!