Difference between [[NSDate date] retain] and [[NSDate alloc] init]

前端 未结 5 1877
醉梦人生
醉梦人生 2021-01-03 10:36

As both of the following serves the same purpose,

today = [[NSDate date] retain];    

and

today = [[NSDate alloc] init]; 
<         


        
5条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-03 11:14

    When you do this:

    [NSDate date];
    

    …a new NSDate is created which will automatically be released (not deallocated!) at the end of the event loop. You can, of course, retain it to keep it around longer.

    When you do this:

    [[NSDate alloc] init];
    

    …a new NSDate is created which you should release when you’re done with it.

    From a memory management standpoint, the main differece between [[NSDate date] retain] and the alternative is that this NSDate will be around at least until the end of the event loop. If you’re just creating a few objects, it doesn’t matter. But, if you create (and release) a lot of objects — say, while processing data in a loop — using the former pattern could cause the memory usage of your application to spike (and then drop suddenly at the end of the event loop). With the latter pattern, the object gets destroyed as soon as you release it.

提交回复
热议问题