for-in中的for-in(Objective-C Fast Enumeration)

时间:2014-06-06 11:41:28

标签: objective-c nsmutablearray

我想一次添加和删除一些UIView 所以,我制作了NSArray并将UIView插入其中 问题是NSArray.count增加了很多倍,应用程序变慢了。

@property (nonatomic, strong) UIView* customView1;
@property (nonatomic, strong) UIView* customView2;
@property (nonatomic, strong) UIView* customView3;
@property (nonatomic, strong) NSMutableArray* viewsArray1;
@property (nonatomic, strong) NSMutableArray* viewsArray2;

- (void)setCustomView
{
    for (self.customView1 in self.viewsArray1)
    {
        if (self.customView1.frame.origin.x <= 100) 
        {
            self.customView2 = [[UILabel alloc]initWithFrame:CGRectMake(self.customView1.center.x + 50, self.customView1.center.y + 50, 50, 50)];
            [self.viewsArray2 addObject:self.customView2];
            for (self.customView2 in self.viewsArray) 
            {
                [self.view addSubview:self.customView2];
            }
        }
        else if (self.customView1.frame.origin.x > 100)
        {
            self.customView3 = [[UILabel alloc]initWithFrame:CGRectMake(self.customView1.center.x + 100, self.customView1.center.y - 50, 50, 50)];
            [self.viewsArray2 addObject:self.customView3];
            for (self.customView3 in self.viewsArray2) 
            {
                [self.view addSubview:self.customView3];
            }
        }
    }
}

- (void)removeCustomView
{
    for (self.customView2 in self.viewsArray2)
    {
        [self.customView2 removeFromSuperview];
    }
    for (self.customView3 in self.viewsArray2)
    {
        [self.customView3 removeFromSuperview];
    }
}

enter image description here

你有什么想要简化这样的代码吗? 谢谢。

2 个答案:

答案 0 :(得分:0)

for (self.customView2 in self.viewsArray2)
{
    [self.customView2 removeFromSuperview];
}

这是快速枚举的错误用法。您应该使用临时变量作为循环的第一个参数:

for (UIView *someView in self.viewsArray2)
{
    [someView removeFromSuperview];
}

如果您将self.customView2作为第一个参数传递,我甚至不知道会发生什么。

答案 1 :(得分:0)

我不太明白为什么你需要这么多视图以及你的添加如何工作,但这里是如何从一行中的数组中删除所有视图

[self.viewsArray2 makeObjectsPerformSelector:@selector(removeFromSuperview)]