我是一个符合 UIAlertViewDelegate 协议的 NSObject - 释放自己合适吗?
我有一个 NSObject (MyCustomObject) 的子类,它被实例化并调用以执行一些逻辑并决定是否显示 UIAlertView。 MyCustomObject 实现了 UIAlertViewDelegate 协议来执行更多逻辑并在alertView:clickedButtonAtIndex:中设置一些NSUserDefaults。 哪里适合释放myCustomObject?如果用户单击警报视图上的某个按钮后不再需要 myCustomObject,则 myCustomObject 可以在alertView 中释放自身: didDismissWithButtonIndex: ?
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
NSLog(@"I'm UIAlertView's Delegate and I'm releasing myself");
[self release];
}
I have a subclass of NSObject (MyCustomObject) that is instantiated and called to perform some logic and decide whether to display a UIAlertView. MyCustomObject implements the UIAlertViewDelegate protocol to perform some more logic and set some NSUserDefaults in alertView: clickedButtonAtIndex:.
Where is it appropriate to release myCustomObject? If myCustomObject is no longer needed after the user clicks one of the buttons on the alert view, it is OK for myCustomObject to release itself in alertView: didDismissWithButtonIndex: ?
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
NSLog(@"I'm UIAlertView's Delegate and I'm releasing myself");
[self release];
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为如果您为自定义对象制定委托协议,然后让该对象的所有者作为其委托,那就更好了。在类的警报视图委托方法中,向自定义委托发送一条消息,以便它可以处理释放您的自定义对象。
如果对象在调用代码中自动释放,或者调用代码尝试手动释放对象本身,则尝试自释放可能会产生意外行为甚至崩溃。
I think it'd be better if you made a delegate protocol for your custom object, then have the owner of that object be its delegate. In your class's alert view delegate method, send the custom delegate a message so it can handle releasing your custom object.
If the object is autoreleased within the calling code, or the calling code tries to manually release your object itself, trying to self-release might produce unexpected behavior or even crash.