ios - 调用 [UIColor colorWithRed :green:blue:alpha:] causing terrible crash

标签 ios objective-c uicolor

总结:

在 UITextField 的子类中:

  • [UIColor colorWithRed:green:blue:alpha] 导致整个应用程序崩溃
  • [UIColor greenColor] 工作正常,没有任何问题

这怎么可能?

答案:

事实证明,问题是我从 layoutSubviews 调用了使用 colorWithRed 的方法。显然 colorWithRed 分配了额外的内存,这会导致问题出现。 (感谢 Johannes Fahrenkrug 在评论中指出它很可能是其他东西——见下文。)

详细信息:

在作为 UITextField 子类的 ECTextField 类中,当我进行以下调用时,我遇到了严重的崩溃:

[self setTextColor:[UIColor colorWithRed:42/255.0 green:170/255.0 blue:42/255.0 alpha:0.8]];

应用卡住、挂起,过了一会儿我收到以下错误:

SampleApp(58375,0x34f71a8) malloc: *** mach_vm_map(size=1048576) failed (error code=3)
*** error: can't allocate region
*** set a breakpoint in malloc_error_break to debug
2013-11-14 22:25:11.929 SampleApp[58375:907] *** Terminating app due to uncaught exception 'NSMallocException', reason: '*** NSAllocateObject(): attempt to allocate object of class 'NSPathStore2' failed'
*** First throw call stack:
(0x2362012 0x2166e7e 0x2361deb 0x1b5bcf2 0x1b60148 0x1bdb7a6 0x120f8a3 0x10ccaf2 0x96b14e4 0x10cc84e 0x96b1542 0x130c42 0x120491 0x120308 0x10fb2dd 0x217a6b0 0x3dbfc0 0x3d033c 0x3d0150 0x34e0bc 0x34f227 0x34f8e2 0x232aafe 0x232aa3d 0x23087c2 0x2307f44 0x2307e1b 0x35647e3 0x3564668 0x10aaffc 0x798d 0x25a5)
libc++abi.dylib: terminate called throwing an exception

奇怪的是,如果我将那行代码替换为以下代码,一切都会正常工作:

[self setTextColor:[UIColor greenColor]];

有谁知道为什么会这样,我可以尝试解决这个问题吗?

感谢您的帮助,

埃里克

最佳答案

问题是你有一个无限循环。 如果您在 UITextField 子类的 layoutSubviews 中调用 [self setTextColor:,则会创建一个无限循环,因为 setTextColor 会导致layoutSubviews 再次调用:UITextView setTextColor changes layout in UITableViewCell

这就是为什么需要一段时间才能出现错误:应用程序内存不足。您可以通过使用 Instruments 运行它来验证这一点。

永远不要从 layoutSubviews 调用任何触发 layoutSubviews 的东西。

关于ios - 调用 [UIColor colorWithRed :green:blue:alpha:] causing terrible crash,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19978609/

相关文章:

ios - 如何在 iOS 中绘制工具提示

ios - 页面 View ScrollView 不是锻炼

ios - OBJC @selector 在另一个实现中不起作用

objective-c - 深层嵌套的 if 语句是否被认为是良好的形式?

ios - Google AdMob 不支持 CocoaPods

ios - swift 中的 barTintColor

iphone - 为什么 initWithPatternImage 会丢失 PNG 的 alpha 值

ios - Sprite Kit - 根据 NSMutableArray 对象列表删除 SKNode

ios - 带有图像的 UIColor 颜色在 IOS 7 下不起作用

ios - Xcode 10 iOS firebase firestore SDK——多个命令在 Firebase 中产生 gRPCCertificates.bundle 错误