I’m trying to learn objective-c and get some problem. I’ve created class Creature and extend it with Dog class.
But when im calling method state, return result looks like it was called from creature class, not Dog.
Link for github source
p.s. If you find anouther bugs and memory leaks points, please report me)
code:
@interface Creature: NSObject
- (NSString *)state;
..
@implementation Creature
- (NSString *)state
{
return [_name stringByAppendingString: ([self isHungry] ? @" is hungry" : @" not hungry")];
}
// Dog
@interface Dog: Creature
..
@implementation Dog
- (NSString *)state
{
return [[super state] stringByAppendingString: ([self isFriendly] ? @" and friendly" : @" and unfriendly")];
}
And calling method
Dog *creature = [Dog CreatureBorn];
NSLog([creature state]);
It looks like you’ve only got a Dog.h and no implementation file (Dog.m).
Because Objective-C is a dynamic language, all classes are created at run-time (Using the objc_allocateClassPair() function, IIRC). By just having a header file, you’re only forward declaring the class and it’s not actually created.
Also, your Dog class isn’t inheriting from Creature, it’s just confirming with the PetProtocol protocol. Protocols in Objective-C are more like interfaces in Java or C#, they’re not classes.
Internally, the Objective-C runtime is very simple. It just boils down to a bunch of C functions and structures. If you’re interested in learning how things work in Objective-C and don’t mind reading C code, I’d highly recommend reading Apple’s Objective-C Runtime Reference.