Search code examples
objective-cnsmutablearrayarc4random

Despite `addObject` , NSMutableArray.count is 1


After adding four _labelView by -addLabel, I'd like to move all _labelView at random by -moveLabel.
LabelView is subclass of UIView.

But in case of this code, I can move only one _labelView I have added at the last.
Looking NSLog(@"%d", _viewsArray.count), it outputs "1".
How do I fix it to move all _labelView?

enter image description here

@property (nonatomic, strong) LabelView* labelView;
@property (nonatomic, strong) NSMutableArray* viewsArray;

- (void)addLabel
{
    _viewsArray = [[NSMutableArray alloc]init];
    _labelView = [[LabelView alloc]initWithFrame:CGRectMake(0, 0, 200, 25)];
    [_viewsArray addObject:_labelView];
    for (_labelView in _viewsArray){
        [self.view addSubview:_labelView];
    }
    NSLog(@"%d", _viewsArray.count);
}

- (void)moveLabel
{
    int n;
    CGPoint labelFrame;
    for (_labelView in _viewsArray)
    {
        n = arc4random() % 4;
        switch (n) {
            case 0: labelFrame = CGPointMake(30, 50);
                break;
            case 1: labelFrame = CGPointMake(30, 100);
                break;
            case 2: labelFrame = CGPointMake(30, 150);
                break;
            case 3: labelFrame = CGPointMake(30, 200);
                break;
            default:
                break;
        }
        [UIView animateWithDuration:0.5f delay:0.0f options:UIViewAnimationCurveEaseIn
                         animations:^{_labelView.center = labelFrame;} completion:^(BOOL finished){}];
    }
    NSLog(@"%d", _viewsArray.count);
}

Solution

  • In your addLabel method you allocate the NSMutableArray every single time you add new label:

    _viewsArray = [[NSMutableArray alloc]init];
    

    so you will have just one object in that array. Simple move this line to viewDidLoad method (or some init method if it;s not view controller subclass) and it should fix it.