So I am new to Objective-C but not to OOP programming. I am trying to make a class that will add "Squares" to a NSMutableArray but when I wrote the class and ran my app, it crashed. Here is the Squares.h file:
#import <Foundation/Foundation.h>
#import "Square.h"
@interface Squares : NSObject {
NSMutableArray *squares; }
-(id) init;
-(void) addSquare: (CGPoint) pos;
-(NSMutableArray *) getSquares;
-(void) update;
-(void) render;
@end
And here is the Squares.m file:
import "Squares.h"
@implementation Squares
-(id) init{ self = [super init]; if (self != nil) { squares = [[NSMutableArray alloc] init];
[self addSquare: CGPointMake(100, 100)]; } return self; }
-(void) addSquare: (CGPoint) pos{ Square *square; square = [[Square alloc] init]; [square setPosition: pos];
[squares addObject: square]; }
-(NSMutableArray *) getSquares{ return squares; }
-(void) update{ for (int i = 0; i < squares.count; i++){ Square *s; s = [squares objectAtIndex: i]; [s move];
} }
-(void) render{ for (int i = 0; i < squares.count; i++){ Square *s; s = [squares objectAtIndex: i]; [s render];
} }
@end
So is this not working just because I have programmed this wrong or not?
[Square alloc]
, you just waste your user's RAM... – user529758 Aug 14 '12 at 17:50[Square alloc]
s in yourupdate
andrender
functions do nothing of value. If you've got ARC on, they're just wasted cycles (unless the compiler manages to remove them, but either way, it's a waste). If you don't have it on, you've got a memory leak. – nil Aug 14 '12 at 17:57