0

或者:这种 UILabel 用法怎么可能生成 NSMutableDictionary NSInvalidArgumentException?

这是一个非 ARC iOS 应用程序。当 showLabel(下)运行时,我会偶尔但很少会看到 [__NSDictionaryM setObject:forKey:] 抛出错误:NSInvalidArgumentException * setObjectForKey: key cannot be nil。

@property (nonatomic, retain) UILabel *myLabel;
@synthesize myLabel = _myLabel;

- (void)showLabel{

if (self.myLabel) {
    return;
}

self.myLabel                        = [[[UILabel alloc] initWithFrame:self.tableView.frame] autorelease];
self.myLabel.textColor              = [UIColor whiteColor];
self.myLabel.shadowColor            = [UIColor blackColor];
self.myLabel.shadowOffset           = CGSizeMake(0, 1);
self.myLabel.textAlignment          = UITextAlignmentCenter;
self.myLabel.text                   = @"blah";
self.myLabel.userInteractionEnabled = YES;
[self.myLabel addGestureRecognizer:[[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(labelTapped:)] autorelease]];
[self.view addSubview:self.myLabel];
[self.view bringSubviewToFront:self.myLabel];

}

- (void)hideLabel {
if (!self.myLabel) {
    return;
}

[self.myLabel removeFromSuperview];
self.myLabel = nil;

}

如果我中断 [__NSDictionaryM setObject:forKey:],它会在 UILabel 的 setTextColor、setShadow、setShadowOffset 和 setTextAlignment 方法中被调用。我发送的任何值都不应该为零,但是这个字典的使用是标签内部的,所以我想知道在发送自动释放后我是否会因为其他一些导致自动释放池的事件而丢失对标签的引用在我仍在使用方法时耗尽(应用程序中涉及多个外部库),因此内部字典的使用偶尔会遇到错误。

在这种情况下,这可能解释 NSMutableDictionary 的 NSInvalidArgumentException 错误吗?

这是完整的堆栈跟踪:

NSInvalidArgumentException *** setObjectForKey: key cannot be nil

1 libobjc.A.dylib 0x3678c963 objc_exception_throw + 31
2 CoreFoundation 0x378625ef -[__NSDictionaryM setObject:forKey:] + 143
3 MyApp 0x000effab -[TableViewController showLabel] (MainTableViewController.m:222)
4 CoreFoundation 0x37851349 _CFXNotificationPost + 1421
5 Foundation 0x37b2d38f -[NSNotificationCenter postNotificationName:object:userInfo:] + 71
6 MyApp 0x000d9141 -[Event setDictionary:] (Event.m:123)
4

1 回答 1

1

我可以肯定地说它与自动释放无关。您的属性具有保留,并且您在存储变量时正确使用了该属性,因此您的保留计数器变为 +1(分配)+1(属性设置器保留)并最终变为 -1(自动释放)

您的问题可能在其他地方,但是如果没有更多代码我无法弄清楚,对不起!

编辑:如果你想玩超级安全(我实际上会推荐这个),你可以这样做:

self.myLabel = [[UILabel alloc] initWithFrame:self.tableView.frame];
// configure
[self.myLabel release];

您的手势识别器也是如此

试试看你是否仍然遇到崩溃

于 2012-12-26T19:54:41.437 回答