Xcode和标签搜索

时间:2015-10-12 04:09:24

标签: ios objective-c

一个简单的询问。

当使用Objective-C / Swift并且决定在故事板中为对象实现标签时,系统如何搜索标签?

它是否接近线性搜索?因此,暗示具有较低数值的标签将更快搜索?或者它完全不同地接近这个?

例如:

UIImageView *imageView = (UIImageView *)[self viewWithTag:1];
        imageView.image = [UIImage imageNamed: @"Elderberries"];

VS

UIImageView *imageView = (UIImageView *)[self viewWithTag:100000000];
        imageView.image = [UIImage imageNamed: @"Motherless_Goat"];

由于

1 个答案:

答案 0 :(得分:0)

我做了一些实验,下面是代码

//adding 30000 tag at first position
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 20, 20)];
label.text = [NSString stringWithFormat:@"%d", 30000];
label.tag = 30000;
[self.view addSubview:label];

for (int i = 0; i < 30000; i++) {
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 20, 20)];
    label.text = [NSString stringWithFormat:@"%d", i];
    label.tag = i;
    [self.view addSubview:label];
}

NSTimeInterval currentTime, fetchTime;
currentTime = CFAbsoluteTimeGetCurrent();
UILabel *label1 = (UILabel *)[self.view viewWithTag:5];
fetchTime = CFAbsoluteTimeGetCurrent();
NSLog(@"Label:%@ = %f",label1.text, fetchTime - currentTime);



currentTime = CFAbsoluteTimeGetCurrent();
UILabel *label2 = (UILabel *)[self.view viewWithTag:100];
fetchTime = CFAbsoluteTimeGetCurrent();
NSLog(@"Label:%@ = %f",label2.text, fetchTime - currentTime);


currentTime = CFAbsoluteTimeGetCurrent();
UILabel *label3 = (UILabel *)[self.view viewWithTag:1000];
fetchTime = CFAbsoluteTimeGetCurrent();
NSLog(@"Label:%@ = %f",label3.text, fetchTime - currentTime);

currentTime = CFAbsoluteTimeGetCurrent();
UILabel *label4 = (UILabel *)[self.view viewWithTag:5000];
fetchTime = CFAbsoluteTimeGetCurrent();
NSLog(@"Label:%@ = %f",label4.text, fetchTime - currentTime);


currentTime = CFAbsoluteTimeGetCurrent();
UILabel *label5 = (UILabel *)[self.view viewWithTag:10000];
fetchTime = CFAbsoluteTimeGetCurrent();
NSLog(@"Label:%@ = %f",label5.text, fetchTime - currentTime);


currentTime = CFAbsoluteTimeGetCurrent();
UILabel *label6 = (UILabel *)[self.view viewWithTag:30000];
fetchTime = CFAbsoluteTimeGetCurrent();
NSLog(@"Label:%@ = %f",label6.text, fetchTime - currentTime);

以下是日志(重新格式化以便比较容易)

Label:5 =     0.000011
Label:100 =   0.000043
Label:1000 =  0.000346
Label:5000 =  0.001169
Label:10000 = 0.002115
Label:30000 = 0.000009

结论:

viewWithTag:将花费更多时间用于更高的标签(仅当有大量对象时),搜索可能是线性的,我认为是这种情况,因为view.subViews为您提供数组的顺序不是由标签添加的。是的,它需要更多的时间,它几乎可以作为线性搜索。

时间取决于添加子视图的索引,在上述情况下30000标记的时间比所有其他标记的最小值,因为它是在第一个索引处添加的。

viewWithTag:的可行实现可能就像这样

- (UIView *)viewWithTag:(NSInteger)tag {
    for (UIView *view in self.subviews) {
        if (view.tag == tag) {
            return view;
        }
    }
    return nil;
}