Objective C - 调用对象返回方法而不使用返回值
我知道即使它有一个返回值(如 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
此调用创建的 NSTimer 由当前 NSRunLoop 对象拥有,因此它不会被任何自动释放池耗尽自动释放。 而且手动释放是错误的。 应通过发送 invalidate 消息来删除 NSTimer:
所以基本上你应该有一个变量并使用 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:
So basically you should have a variable for it and use invalidate instead of release