我有几个遵循以下设置模式的 UIView 子类(按钮、标签等)。我的问题是,为什么release
之后消息仍然能够发送到UILabel
?
myLabel = [[UILabel alloc] initWithFrame:someFrame];
[someUIView addSubview:myLabel];
[myLabel release];
myLabel.textAlignment = UITextAlignmentCenter;
// other property changes to myLabel
我想它们是由新的 UIView“拥有”的,但我不明白为什么 release
不会破坏原始对象,从而破坏它的所有消息。我没有通过 someUIView
的 subViews
进行属性更改。我没有提示。我只是想了解为什么。
编辑:我应该补充一点,这些是实例变量,如果这有影响的话。
最佳答案
只要保留计数大于 0,该对象就不会被销毁。在这种情况下,someUIView
保留了该对象。
释放对象后最好不要再访问它。更好的模式可能是:
myLabel = [[[UILabel alloc] initWithFrame:someFrame] autorelease];
myLabel.textAlignment = UITextAlignmentCenter;
[someUIView addSubview:myLabel];
myLabel = nil;
第二个例子:
myLabel = [[UILabel alloc] initWithFrame:someFrame];
[someUIView addSubview:myLabel];
myLabel.textAlignment = UITextAlignmentCenter;
// other property changes to myLabel
[myLabel release];
myLabel = nil;
关于iphone - 向已释放的对象发送消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8556023/