2

假设我有这个代码:

NSString *inspDate = @"20120515";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyyMMdd"];
NSDate *inspectionDate;
inspectionDate = [dateFormatter dateFromString:inspDate];

当我检查它是否有效(NSDate包含格式正确的数据)时,它确实有效……但为什么呢?

在这里,我将执行以下步骤:

  1. 内存NSDateFormatter在堆中被分配和实例化。dateFormatter指向那个位置,明白了:

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    
  2. 现在dateFormatter被告知如何将NSString's 解释为日期,好的:

    [dateFormatter setDateFormat:@"yyyyMMdd"];
    
  3. 这是我模糊的部分,inspectionDate指针设置为零。它没有指向任何东西:

    NSDate *inspectionDate;
    
  4. 当没有或调用到时如何dateFormatter返回指向 a 的指针?是在执行中做和在执行吗?NSDateallocinitinspectionDatedateFromStringallocinit

     inspectionDate = [dateFormatter dateFromString:inspDate];
    

帮助我想象这将是一个巨大的帮助。谢谢!

4

1 回答 1

2

The dateFromString method will instantiate (likely through an alloc/init call at some point, or an NSDate convenience method which itself will do the allocation) an NSDate object and you assign it to your inspectionDate variable. As with any "convenience" method that does not start with alloc, new, or copy, there is no transfer of object ownership, i.e. the instance returned is autoreleased.

于 2012-12-01T18:17:55.270 回答