Let’s say I have this code:
NSString *inspDate = @"20120515";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyyMMdd"];
NSDate *inspectionDate;
inspectionDate = [dateFormatter dateFromString:inspDate];
When I check to see that it works (NSDate contains the correctly formatted data) it does… but why?
Here I go through the steps:
-
Memory for
NSDateFormatteris getting allocated and instantiated in the heap.dateFormatteris pointing to that location, got it:NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; -
Now
dateFormatteris being told how to interpretNSString‘s as a date, ok:[dateFormatter setDateFormat:@"yyyyMMdd"]; -
Here’s the part I’m hazy on,
inspectionDatepointer is set to nil. It’s not pointing to anything:NSDate *inspectionDate; -
How is
dateFormatterreturning a pointer to aNSDatewhen there was noallocorinitcalled toinspectionDate? Is the implementation ofdateFromStringdoing theallocandinitin its implementation?inspectionDate = [dateFormatter dateFromString:inspDate];
Helping me visualize this would be a tremendous help. Thank you!
The
dateFromStringmethod will instantiate (likely through an alloc/init call at some point, or anNSDateconvenience method which itself will do the allocation) anNSDateobject and you assign it to yourinspectionDatevariable. As with any “convenience” method that does not start withalloc,new, orcopy, there is no transfer of object ownership, i.e. the instance returned is autoreleased.