1

概括:

在 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]];

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

谢谢你的帮助,

埃里克

4

3 回答 3

7

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

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

layoutSubviews永远不要从触发器中调用任何东西layoutSubviews

于 2013-11-14T13:57:19.877 回答
6

将其更改为

[self setTextColor:[UIColor colorWithRed:42.0f/255.0f green:170.0f/255.0f blue:42.0f/255.0f alpha:0.8f]];

颜色对象的分量,指定为 0.0 到 1.0 之间的值。

于 2013-11-14T13:16:27.503 回答
1

为颜色创建类别是最好的。您可以在任意多的地方重用您的代码。

如何创建类别?

如果你按下command+n它会显示一个文件选项Category。从那里选择或创建一个名为UIColor+custom.h.m命名的 .h 文件UIColor+custom.m

.m文件中定义一个方法:

+ (UIColor *)myColor
{
    return [UIColor colorWithRed:42.0/255.0 green:170.0/255.0 blue:42.0/255.0  alpha:0.8];
}

.h并在文件中声明此方法:

+ (UIColor *) myColor;

现在viewController像这样导入这个类别:

#import "UIColor+custom.h"

现在给你的 UITextField 文本颜色是这样的:

[self setTextColor:[UIColor myColor]];

希望这可以帮助。

于 2013-11-14T13:22:59.050 回答