I have a custom class MDRect that i am trying to add an NSMutableArray
the array is a property:
@property (retain) NSMutableArray* array;
it is initialized in the initMethod of the NSView subclass:
-(id)init {
array = [NSMutableArray new];
return [super init];
}
then i am trying to add an object in the array here:
-(void)mouseUp:(NSEvent *)theEvent
{
NSPoint mouseLoc = [NSEvent mouseLocation];
mouseLoc = [self mouse:mouseLoc inRect:[self frame]];
CGSize temp;
NSLog(@"%f",mouseLoc.y - mouseLocation.y);
NSLog(@"%f",mouseLoc.x - mouseLocation.x);
temp.height = mouseLoc.y - mouseLocation.y;
temp.width = mouseLoc.x - mouseLocation.x;
tempRect.size = temp;
MDRect * rect = [[MDRect alloc] initWithColor:[NSColor orangeColor] andRect:tempRect];
[array addObject:rect];
int i = (int)array.count;
NSLog(@"%i",i);
[self setNeedsDisplay:YES];
}
But the object being is not being added to the array. it never returns any value other than 0 in the NSLog function. What am I doing wrong?
Your problem is your
initmethod. You’ve got it quite wrong and it should look like this:Your problem is that you’re not calling
super‘s init and assigning that toselfand then setting uparray. You’re assigningarraybefore you’ve even got a proper object and then you’re not even returning anything thatarrayhas been set on, but rather returning the result of the super-class’sinitmethod. Then when you go to logarray.count,arrayisniland henceibecomes0(because messagingnilreturns 0 in this circumstance).