我是一个符合 UIAlertViewDelegate 协议的 NSObject - 释放自己合适吗?

发布于 2024-10-28 15:18:21 字数 512 浏览 6 评论 0原文

我有一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

水晶透心 2024-11-04 15:18:21

我认为如果您为自定义对象制定委托协议,然后让该对象的所有者作为其委托,那就更好了。在类的警报视图委托方法中,向自定义委托发送一条消息,以便它可以处理释放您的自定义对象。

如果对象在调用代码中自动释放,或者调用代码尝试手动释放对象本身,则尝试自释放可能会产生意外行为甚至崩溃。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文