Search code examples
iosobjective-cnsmutablearrayuitapgesturerecognizer

How to add objects in NSMutableArray with for loop?


Here, the issue is nothing but I don't know much about objectiveC. So the query is that I am working on a project where user taps on Image and with UITapGestureRecognizer I have to store that tapped position in my array. I don't know how is this possible that every time user taps the view and CGPoint value gets stored in NSMutableArray.

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

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

Solution

  • You need to subclass UIView and implement the method - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event to get a touch callback. Second, a touch location (CGPoint) cannot be added to an NSMutableArray, but a wrapper class for it can (NSValue). Here would be a very basic implementation of what you are going for.

    // 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];
    }
    

    If you want to loop through these touch locations later, all you have to to is fast enumerate through the array and unwrap the NSValues.

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