How do I know when to release an NSDate object?

限于喜欢 提交于 2019-12-10 18:18:40

问题


Do either or both of these date pointers requires a [release] when I'm done with them. How would i know this? I'm unsure since I'm not doing init explicitly.

NSDate *date = [NSDate date];

NSDate *date = [dateWithTimeIntervalSince1970:100000000];

回答1:


Both are autoreleased, that is you don't need to release them yourself. The rule of thumb is that you own an object if you send +alloc or -copy or explicitly retain it:

  • [[SomeClass alloc] init...]
  • [someObject copy]
  • [some object retain]

If you own an object you must release it. +new is a shortcut to +alloc and -init.




回答2:


No, both of the returned dates from those methods are autoreleased. You don't need to worry about their memory management, though to be a good citizen, setting the pointer to nil when you're done with them would be a good idea.

As a general rule, you can follow what I call the "CARN" rule. in Cocoa/Cocoa Touch any method that has the words Copy, Alloc, Retain, or New in them will return objects that need to be released by you at some point. These are naming conventions applied to methods that return objects with a retain count of +1. The class that calls these methods "owns" the object and is responsible for releasing it when it's finished with it.

Hope this helps.



来源:https://stackoverflow.com/questions/2192520/how-do-i-know-when-to-release-an-nsdate-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!