使用NSMutableArray崩溃的类?

时间:2012-08-14 17:47:41

标签: objective-c ios5 nsmutablearray

所以我是Objective-C的新手,但不是OOP编程。我正在尝试创建一个将“Squares”添加到NSMutableArray的类,但是当我编写该类并运行我的应用程序时,它崩溃了。这是Squares.h文件:

#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

这是Squares.m文件:

  

导入“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 alloc] init];       [square setPosition:pos];

[squares addObject: square]; }
     

- (NSMutableArray *)getSquares {       返回广场; }

     

- (void)update {       for(int i = 0; i&lt; squares.count; i ++){           Square * s;           s = [square objectAtIndex:i];           [s move];

} }
     

- (void)render {       for(int i = 0; i&lt; squares.count; i ++){           Square * s;           s = [square objectAtIndex:i];           [s渲染];

} }
     

@end

这是不是因为我编程错误了?

2 个答案:

答案 0 :(得分:2)

而不是for (int i = 0; i <= squares.count; i++

尝试for (int i = 0; i < squares.count; i++

答案 1 :(得分:0)

正如其他人所指出的那样,Square *s = [Square alloc];update方法中的render无用。

正如安德烈告诉你的那样,for (int i = 0; i <= squares.count; i++)会计算得太远,你应该使用<代替<=

更好的是:

-(void) update{
    [squares makeObjectsPerformSelector:@selector(move)]; }

-(void) render{
    [squares makeObjectsPerformSelector:@selector(render)]; }