Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

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.

like image 628
iand675 Avatar asked Nov 11 '10 01:11

iand675


1 Answers

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!
like image 63
Jesse Beder Avatar answered Nov 08 '22 16:11

Jesse Beder