开发者

is this correct re returning a date re memory management?

开发者 https://www.devze.com 2023-03-06 13:39 出处:网络
is this correct re returning a date re memory management? The assumption here I have is I want to return a date back to the caller, but I don\'t want the caller to be able to be change the date and i

is this correct re returning a date re memory management?

The assumption here I have is I want to return a date back to the caller, but I don't want the caller to be able to be change the date and impact the method's date, hence I thought I would return a copy.

So the code in the method I have is:

- (NSDate*)dateForMyTest {
     return [[self.endDate copy] autorelease];
}

I was assuming I have to autorelease it so the caller doesn't have to, as they would开发者_StackOverflow not have called an init/copy/etc themselves.


It may work, but creating a copy is not necessary. NSDate is immutable and cannot be edited later.

This should suffice...

- (NSDate*)dateForMyTest {
     return self.endDate;
}


You are correct, as far as it goes. But note that NSDate is immutable, so there is really no reason not to just return self.endDate.


Yes, that is correct. Because the method name didn't include init/copy/new, you should autorelease.


The copy autorelease may be needed if the app is using nsoperations/threads, etc. But you may be already thread safer - or not: When you use

return self.endDate

any number of things could be happening, depending on how the property was set up. Was it

 @property (retain) endDate; 

, or the more common, faster and less thread safe

 @property (nonatomic, retain) endDate; 

It is as complicated as you like!

What's the difference between the atomic and nonatomic attributes?

0

精彩评论

暂无评论...
验证码 换一张
取 消