kusumoto_teruya
kusumoto_teruya

Reputation: 2475

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);
}

Upvotes: 0

Views: 84

Answers (3)

Sulthan
Sulthan

Reputation: 130082

The most simple fix...

- (void)addLabel {
    if (_viewsArray == nil) {
        _viewsArray = [[NSMutableArray alloc] init];
    }

Upvotes: 0

Greg
Greg

Reputation: 25459

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.

Upvotes: 4

MeXx
MeXx

Reputation: 3357

You are allocating a new _viewsArray everytime addView is called! You should rather allocate the Array at viewDidLoad or something, and then just use it

Upvotes: 0

Related Questions