为什么我的CGPoint不能正确保存在NSMutable数组中?

时间:2011-06-16 20:24:33

标签: iphone uiview cgpoint

所以,我的代码基于How can I add CGPoint objects to an NSArray the easy way?

的答案

我的代码现在读起来像:

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch * touch = [touches anyObject];
    locationOne = [touch locationInView: [UIApplication sharedApplication].keyWindow];
    NSLog(@"In touchesBegan");
    NSLog(@"x is: %.3f.  y is: %.3f", locationOne.x, locationOne.y);
    [points addObject:[NSValue valueWithCGPoint:locationOne]];
    NSValue *val = [points objectAtIndex:[points count]];
    CGPoint p = [val CGPointValue];
    NSLog(@"in points array:  x is: %.3f, y is: %.3f", p.x ,p.y);
}

2011-06-16 13:21:57.367 canvas_test[7889:307] In touchesBegan
2011-06-16 13:21:57.371 canvas_test[7889:307] x is: 115.000.  y is: 315.500
2011-06-16 13:21:57.374 canvas_test[7889:307] in points array:  x is: 0.000, y is: 0.000
2011-06-16 13:22:00.982 canvas_test[7889:307] In touchesBegan
2011-06-16 13:22:00.985 canvas_test[7889:307] x is: 274.500.  y is: 386.000
2011-06-16 13:22:00.988 canvas_test[7889:307] in points array:  x is: 0.000, y is: 0.190
2011-06-16 13:22:11.476 canvas_test[7889:307] In touchesBegan
2011-06-16 13:22:11.480 canvas_test[7889:307] x is: 105.500.  y is: 140.500
2011-06-16 13:22:11.483 canvas_test[7889:307] in points array:  x is: 0.000, y is: 0.190

有人知道可能出现什么问题吗?

编辑:

我注意到,无论何时检查点数,它总是为0.有没有办法检查我是否正确初始化了我的NSMutableArray?我用 points = [[NSMutableArray alloc] init]; 在init函数中,并且具有NSMutableArray * points;在我的.h文件中。我是否还需要做更多的事情来启动NSMutableArray?

2 个答案:

答案 0 :(得分:3)

我很惊讶这不会崩溃。你正在阅读超出数组末尾的内容:

NSValue *val = [points objectAtIndex:[points count]];

这应该是:

NSValue *val = [points objectAtIndex:[points count] - 1];

NSValue *val = [points lastObject];

答案 1 :(得分:1)

[points objectAtIndex:[points count]]将永远超出范围。数组中的最后一个对象将位于索引[points count] - 1

或者您可以使用NSValue *val = [points lastObject]