简体   繁体   中英

The lifetime of instance of object in ObjC

I'm still little bit perplexed by pointers and memory management (starting out with ObjC and Cocoa). What got me thinking, is this piece of code:

double seconds = [[NSDate date] timeIntervalSince1970];

This is what I understand:

  1. I get value of float type returned from calling method/message on NSDate class
  2. This value gets stored in variable seconds

What I don't understand is am I creating NSDate object (=instance of class NSDate ) at all? Is this object only temporary? I always thought that the way to create an object and have the object to be persistent (at least until ARC steps in or it is destroyed when function ends) is to create a pointer to it. Maybe like this:

NSDate *now = [NSDate date];
[now timeIntervalSince1970] // get the value

Does this mean that in my original example, there is some unnamed (no variable pointing to it) instance of NSDate created on the heap and once it returns the float value it gets removed from heap?

Does this mean that in my original example, there is some unnamed (no variable pointing to it) instance of NSDate created on the heap and once it returns the float value it gets removed from heap?

Yes, that's exactly right.

ARC will remove the object when it goes out of scope.

Even before ARC, the object would be created as autorelease and be released the next time through the event loop (or whenever the nearest autorelease pool was drained).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM