【问题标题】:How to add objects in NSMutableArray with for loop?如何使用 for 循环在 NSMutableArray 中添加对象?
【发布时间】:2014-08-02 05:52:28
【问题描述】:

在这里,问题没什么,但我对objectiveC 了解不多。所以问题是我正在做一个项目,用户点击图像并使用UITapGestureRecognizer 我必须将点击的位置存储在我的array 中。我不知道每次用户点击viewCGPoint 值时,这怎么可能存储在NSMutableArray 中。

dataArray = [[NSMutableArray alloc] init];
for (NSInteger i = 0; i < [getResults count]; i++) {

[dataArray addObject:tappedPoint];
NSLog(@"RESULT TEST %@", dataArray);
}

【问题讨论】:

  • 你尝试过什么?
  • THIS 回答您的问题。您必须自己尝试一下。
  • [yourArray addObject:[NSValue valueWithCGPoint: point]];
  • @iProgrammer 谢谢,这也有效。

标签: ios objective-c nsmutablearray uitapgesturerecognizer


【解决方案1】:

您需要继承UIView 并实现方法- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 以获得触摸回调。其次,触摸位置 (CGPoint) 不能添加到 NSMutableArray,但它的包装类可以 (NSValue)。这将是您想要实现的一个非常基本的实现。

// in UIView subclass
// Precondition: you have an NSMutableArray named `someMutableArray'
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    CGPoint touchLocation = [[touches anyObject] locationInView:self];
    NSValue *wrapper = [NSValue valueWithCGPoint:touchLocation];

    [someMutableArray addObject:wrapper];
}

如果您想稍后遍历这些触摸位置,您所要做的就是快速枚举数组并解开NSValues。

for (NSValue *wrapper in someMutableArray) {
    CGPoint touchLocation = [wrapper CGPointValue];
}

【讨论】:

  • 谢谢 Brian Tracy,你的意思是我不需要实现任何 for 循环,对吧?
  • @SushilSharma 否,除非您想稍后循环遍历所有触摸位置。
  • 好的,所以使用这段代码,每次用户点击视图时,它都会一个接一个地添加对象。
  • 感谢 Brian Tracy,非常感谢您的出色解决方案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-03-13
  • 1970-01-01
  • 1970-01-01
  • 2019-11-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多