Search code examples
objective-cinheritanceinitsubclassing

Subclassing and Adding init Method Always Returns nil


I'm trying to subclass the UIImage class and add a custom init method with some added variables. However, when I try and create a new object using the new initializer the object is always nil. The new init method is below:

- (id)initWithLat:(int)latitude andLong:(int)longitude andSize:(int)size {
    self = [super initWithContentsOfFile:@"dot.png"];
    if (self) {
        self.lat = latitude;
        self.longi = longitude;
        self.dotScale = size;
    }
    return self;
}

I believe I'm subclassing correctly, here's my header file:

#import <UIKit/UIKit.h>

@interface Dot : UIImage {
    int lat;
    int longi;
    int dotScale;
}

@property  int lat;
@property  int longi;
@property  int dotScale;

- (id)initWithLat:(int)latitude andLong:(int)longitude andSize:(int)size;

@end

I'm getting the error when trying to add a Dot object to a NSMutableArray.

dots = [[NSMutableArray alloc] init];
[dots addObject:[[Dot alloc] initWithLat:0 andLong:0 andSize:1]];

My guess is there's something wrong in the new initializer. I was using this as a guide.


Solution

  • initWithContentsOfFile: returns nil if the file can't be found. Can it be found? Use logging/breakpoints to find out what's going on during your initalizer.