Objective C - 调用对象返回方法而不使用返回值

发布于 2024-08-02 03:26:58 字数 460 浏览 2 评论 0原文

我知道即使它有一个返回值(如 printf),也可以像调用 void 一样调用一个方法,但是这又如何呢?

[NSTimer scheduledTimerWithTimeInterval:0.3 target:self selector:@selector(method) userInfo:nil repeats:NO];

我可以让它浮动在那里而不使用它返回的对象吗? 这就像调用 [NSObject alloc] 而不将其分配给指针或任何东西。 这是内存泄漏吗? 原因是我不想将它分配给变量(计时器),因为如果我释放(或自动释放)它会在触发之前被删除。 而且我不想使用 ivar。 所以我该怎么做?

编辑:我发现了 [self PerformSelector:@selector(myMethod) withObject:nil afterDelay:0.3]; 这比使用计时器要好得多。

I know its fine to call a method as if it was void even though it has a return value (like printf), but what about this?

[NSTimer scheduledTimerWithTimeInterval:0.3 target:self selector:@selector(method) userInfo:nil repeats:NO];

Can I just have that floating there without using the object it returns? That's like calling [NSObject alloc] without assigning that to a pointer or anything. Is that a memory leak? The reason is I don't want to assign it to a variable (the timer) because then if I release (or autoreleaase) it gets deleted before it fires. And I don't want to use an ivar. So what should I do?

EDIT: I found out about [self performSelector:@selector(myMethod) withObject:nil afterDelay:0.3]; which is much better for this than using the timer.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

浅浅 2024-08-09 03:26:58

此调用创建的 NSTimer 由当前 NSRunLoop 对象拥有,因此它不会被任何自动释放池耗尽自动释放。 而且手动释放是错误的。 应通过发送 invalidate 消息来删除 NSTimer:

要请求从 NSRunLoop 对象中删除计时器,请从安装计时器的同一线程向计时器发送无效消息。 该消息立即禁用计时器,因此它不再影响 NSRunLoop 对象。 运行循环会在 invalidate 方法返回之前或稍后的某个时刻删除并释放计时器。

所以基本上你应该有一个变量并使用 invalidate 而不是 release

NSTimer created by this call is owned by current NSRunLoop object, so it is not going to be autoreleased by any autorelease pool drain. And it's wrong to release it manually. NSTimer should be removed by sending it invalidate message:

To request the removal of a timer from an NSRunLoop object, send the timer the invalidate message from the same thread on which the timer was installed. This message immediately disables the timer, so it no longer affects the NSRunLoop object. The run loop removes and releases the timer, either just before the invalidate method returns or at some later point.

So basically you should have a variable for it and use invalidate instead of release

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