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.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With