gpt4 book ai didi

ios - 这种 autoRelease 的用法有什么潜在的问题吗?

转载 作者:行者123 更新时间:2023-11-29 04:13:28 25 4
gpt4 key购买 nike

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

这是一个非 ARC iOS 应用程序。当 showLabel (如下)运行时,我偶尔会(但很少见)看到 [__NSDictionaryM setObject:forKey:] 抛出错误: NSInvalidArgumentException * setObjectForKey: key can not 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)

最佳答案

我可以有把握地说它与自动释放无关。你的属性有一个保留,并且你在存储变量时正确地使用了该属性,所以你的保留计数器变为+1(分配)+1(属性 setter 保留)并最终-1(自动释放)

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

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

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

手势识别器也是如此

尝试一下,看看是否仍然会崩溃

关于ios - 这种 autoRelease 的用法有什么潜在的问题吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14045443/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com