iOS UIView继承性能不好
iOS UIView inheritance bad performance
我只是想对我的项目 iOS 进行性能测试,我对这种行为感到有点惊讶:
在一个简单的 SingleView 应用程序中,如果我从 viewDidLoad
: 主控制器方法在矩形 (20, 20, 200, 200) 上添加 1000 UITextField
,效果很好。这很愚蠢,但它确实有效。
现在我创建我的 class “MyTextField
” 继承自 UITextField
并实现 drawRect: 。 drawRect: 实现什么也不做,我也没有覆盖 UITextField
的任何其他方法。我将我的 1000 UITextField
替换为 MyTextField
class,然后惊奇:它崩溃了。更糟糕的是,我的 iPhone 重启了!
我不明白为什么。根据 Apple 文档,我的 drawRect 不需要调用 super。我也尝试调用 super drawRect:
但结果是一样的。由于“Receive memory warning
”重新启动。
请问有解释吗?
编辑:要清楚:
它崩溃了(我的 iPhone 重新启动):
@implementation MyTextField
-(void)drawRect:(CGRect)rect {
[super drawRect:rect];
}
@end
它也崩溃了(我的 iPhone 重新启动):
@implementation MyTextField
-(void)drawRect:(CGRect)rect {
// or does nothing
}
@end
有效:
@implementation MyTextField
@end
这是我的 ViewController :
- (void)viewDidLoad {
[super viewDidLoad];
NSLog(@"######### START ###########");
for (int i = 0 ; i < 1000 ; i++) {
MyTextField *tf = [[MyTextField alloc] initWithFrame:CGRectMake(20, 20, 200, 200)];
[self.view addSubview:tf];
}
NSLog(@"######### END ###########");
}
它什么都不做
他们警告您 drawRect 的空白实现会影响性能
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
我认为不能保证 super 具有 drawRect 的实现。
所以调用 [super drawRect:rect] 可能会导致崩溃。
之所以影响性能,是因为视图通常不使用drawRect 来绘制自身。
如果你实现 drawRect,GPU 需要将这部分卸载到 CPU(称为离屏渲染)。
我猜您认为实现 drawRect 会覆盖超类中的方法。
但是您应该更多地考虑检查 drawRect 是否存在的超类(例如 respondsToSelector)并仅在这种情况下调用它。
我只是想对我的项目 iOS 进行性能测试,我对这种行为感到有点惊讶:
在一个简单的 SingleView 应用程序中,如果我从 viewDidLoad
: 主控制器方法在矩形 (20, 20, 200, 200) 上添加 1000 UITextField
,效果很好。这很愚蠢,但它确实有效。
现在我创建我的 class “MyTextField
” 继承自 UITextField
并实现 drawRect: 。 drawRect: 实现什么也不做,我也没有覆盖 UITextField
的任何其他方法。我将我的 1000 UITextField
替换为 MyTextField
class,然后惊奇:它崩溃了。更糟糕的是,我的 iPhone 重启了!
我不明白为什么。根据 Apple 文档,我的 drawRect 不需要调用 super。我也尝试调用 super drawRect:
但结果是一样的。由于“Receive memory warning
”重新启动。
请问有解释吗?
编辑:要清楚:
它崩溃了(我的 iPhone 重新启动):
@implementation MyTextField
-(void)drawRect:(CGRect)rect {
[super drawRect:rect];
}
@end
它也崩溃了(我的 iPhone 重新启动):
@implementation MyTextField
-(void)drawRect:(CGRect)rect {
// or does nothing
}
@end
有效:
@implementation MyTextField
@end
这是我的 ViewController :
- (void)viewDidLoad {
[super viewDidLoad];
NSLog(@"######### START ###########");
for (int i = 0 ; i < 1000 ; i++) {
MyTextField *tf = [[MyTextField alloc] initWithFrame:CGRectMake(20, 20, 200, 200)];
[self.view addSubview:tf];
}
NSLog(@"######### END ###########");
}
它什么都不做
他们警告您 drawRect 的空白实现会影响性能
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
我认为不能保证 super 具有 drawRect 的实现。 所以调用 [super drawRect:rect] 可能会导致崩溃。
之所以影响性能,是因为视图通常不使用drawRect 来绘制自身。 如果你实现 drawRect,GPU 需要将这部分卸载到 CPU(称为离屏渲染)。
我猜您认为实现 drawRect 会覆盖超类中的方法。 但是您应该更多地考虑检查 drawRect 是否存在的超类(例如 respondsToSelector)并仅在这种情况下调用它。