iphone - 向已释放的对象发送消息?

标签 iphone objective-c cocoa-touch cocoa

我有几个遵循以下设置模式的 UIView 子类(按钮、标签等)。我的问题是,为什么release之后消息仍然能够发送到UILabel

    myLabel = [[UILabel alloc] initWithFrame:someFrame];
    [someUIView addSubview:myLabel];
    [myLabel release];

     myLabel.textAlignment = UITextAlignmentCenter;

     // other property changes to myLabel

我想它们是由新的 UIView“拥有”的,但我不明白为什么 release 不会破坏原始对象,从而破坏它的所有消息。我没有通过 someUIViewsubViews 进行属性更改。我没有提示。我只是想了解为什么。

编辑:我应该补充一点,这些是实例变量,如果这有影响的话。

最佳答案

只要保留计数大于 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/

相关文章:

objective-c - 切换选项卡时没有获取 viewDidLoad 或 Appear——我可以使用 NSNotification 吗?

iphone - iphone 的 UIScrollView 捕捉到它不应该的边界

iphone - 标签栏+导航栏

ios - NSError 没有被填充

iphone - UITableViewCell 背景 View /图像

ios - UIImageView+AFNetworking - 需要滚动 UICollectionView 来设置图像

iphone - 苹果商店接受,允许下载布局提示到 iphone?

iphone - 为什么此代码会引发 "CoreData: error: (19) PRIMARY KEY must be unique"错误?

iphone - UITableView在离开框架时在单元格上随机滴答

ios - 在 UISearchBar 中设置取消按钮的样式