【问题标题】:how to store CGPoint in array如何将CGPoint存储在数组中
【发布时间】:2011-10-07 14:09:47
【问题描述】:

嗨,我正在尝试将移动点存储在 NSMutableArray 中,所以我有这样的尝试

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *move = [[event allTouches] anyObject];
    CGPoint MovePoint = [move locationInView:self.view];
if (MovePointsArray==NULL) {
        MovePointsArray=[[NSMutableArray alloc]init];
    }
    [MovePointsArray arrayWithObjects:[NSValue valueWithCGPoint:MovePoint]];
}

但这不起作用如何将这些点存储在NSMutableArray

【问题讨论】:

    标签: iphone objective-c xcode cocoa-touch


    【解决方案1】:

    你应该在最后一行使用 addObject::

    -(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
    {
    UITouch *move = [[event allTouches] anyObject];
        CGPoint MovePoint = [move locationInView:self.view];
    if (MovePointsArray==NULL) {
            MovePointsArray=[[NSMutableArray alloc]init];
        }
        [MovePointsArray addObject:[NSValue valueWithCGPoint:MovePoint]];
    }
    

    【讨论】:

      【解决方案2】:

      你应该这样做:

      -(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
      {
          UITouch *move = [[event allTouches] anyObject];
          CGPoint MovePoint = [move locationInView:self.view];
      
          if (MovePointsArray == NULL) {
              MovePointsArray = [[NSMutableArray arrayWithObjects:[NSValue valueWithCGPoint:MovePoint, nil];
          }
          else {
              [MovePointsArray addObject:[NSValue valueWithCGPoint:MovePoint]];
          }
      }
      

      不要忘记保留/释放数组,因为您看不到使用属性访问器。

      最好,您应该在 init 方法中分配/初始化数组,然后只在此处执行:

      -(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
      {
          UITouch *move = [[event allTouches] anyObject];
          CGPoint MovePoint = [move locationInView:self.view];
      
          [MovePointsArray addObject:[NSValue valueWithCGPoint:MovePoint]];
      }
      

      【讨论】:

        【解决方案3】:

        如果要使用方法arrayWithObjects 获取数组,还必须添加nil 作为数组的最后一个元素。

        像这样:

        [MovePointsArray arrayWithObjects:[NSValue valueWithCGPoint:MovePoint], nil];
        

        但是要将对象添加到现有数组中,您应该使用addObject 方法

        [MovePointsArray addObject:[NSValue valueWithCGPoint:MovePoint]];
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-08-18
          • 1970-01-01
          • 1970-01-01
          • 2015-07-11
          • 1970-01-01
          • 2018-02-08
          相关资源
          最近更新 更多