I am trying to create an instance of a class, Dog, but the compiler does not recognize the class and won’t instantiate it. I tried copying the initializers from Pet, the superclass, into Dog, but that didn’t make it work. Why can’t I instantiate the Dog object?
Pet.h
#import <Foundation/Foundation.h>
@interface Pet : NSObject
{
// Some ivars
}
//Randomizer
+(id)randomPet;
//Initializer
-(id)initName:(NSString *)name
initColor:(NSString *)color
initBreed:(NSString *)breed;
// Getters and setters...
@end
Pet.m
#import "Pet.h"
@implementation Pet
+(id)randomPet
{
// Empty
}
-(id)initName:(NSString *)name
initColor:(NSString *)color
initBreed:(NSString *)breed;
{
self = [super init];
if(self)
{
// Initialization...
}
return self;
}
@end
Dog.h
#import "Pet.h"
@interface Dog : Pet
-(id)initName:(NSString *)name initColor:(NSString *)color
initBreed:(NSString *)breed;
// Getters and setters...
@end
Dog.m
#import "Dog.h"
@implementation Dog
+(id)RandomPet
{
// Snip...
}
- (id)initName:(NSString *)name
initColor:(NSString *)color
initBreed:(NSString *)breed;
{
self = [super init];
if(self) {
// Initialization...
}
return self;
}
main.m
#import <Foundation/Foundation.h>
#import "Pet.h"
int main(int argc, const char * argv[])
{
@autoreleasepool
{
Dog *d = [[Dog alloc] init]];
}
return 0;
}
You have following errors:
Instead of
#import Pet.huse#import Dog.hDog *d = [[Dog alloc] init]];should beDog *d=[Dog alloc]init];No need to re-define same method in sub class as they are in super class.
Apart from these answer, I would like to add few more things, these are not errors but it will add to your cocoa programming style and habbit :
The method
does not go with standards, it should have been as :
In the following lines
What about initializing with
petID=0;? If its garbage value become 1 then it will never enter the loop.You can use @property to create property.