Getting the class object of the instance you have, [object class]
and sending a message to that, is exactly how this is supposed to work. Classes are objects too in ObjC, and you can send the same message to different classes in exactly the same way you can send intValue
to either an NSString
or an NSNumber
instance (or, init
to (nearly) any instance!). This is fundamental to ObjC - the method is looked up based on the message at runtime. If this line:
[[object1 class] idString];
isn't compiling, then you have an error elsewhere. That's completely legal and the way you do what you're describing.
#import <Foundation/Foundation.h>
@interface Johnathan : NSObject
+ (NSString *)aNaughtyPhrase;
@end
@implementation Johnathan
+ (NSString *)aNaughtyPhrase
{
return @"Knickers";
}
@end
@interface Johnny : Johnathan @end
@implementation Johnny
+ (NSString *)aNaughtyPhrase
{
return @"Botty";
}
@end
@interface John : Johnathan @end
@implementation John
+ (NSString *)aNaughtyPhrase
{
return @"Woo-woo";
}
@end
@interface Jack : Johnathan @end
@implementation Jack
+ (NSString *)aNaughtyPhrase
{
return @"Semprini";
}
@end
int main(int argc, const char * argv[])
{
@autoreleasepool {
Johnathan * jt = [Johnathan new];
Johnny * jy = [Johnny new];
John * jn = [John new];
Jack * jk = [Jack new];
NSLog(@"%@", [[jt class] aNaughtyPhrase]);
NSLog(@"%@", [[jy class] aNaughtyPhrase]);
NSLog(@"%@", [[jn class] aNaughtyPhrase]);
NSLog(@"%@", [[jk class] aNaughtyPhrase]);
}
return 0;
}