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

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

As both of the following serves the same purpose,

today = [[NSDate date] retain];    

and

today = [[NSDate alloc] init]; 
<         


        
5条回答
  •  猫巷女王i
    2021-01-03 11:05

    Most of the time, when a class has an autoreleased initializer - it looks like this:

    return [[[NSDate alloc] init] autorelease];
    

    So when you call [[NSDate date] retain];, you are effectively calling

    [[[[NSDate alloc] init] autorelease] retain];
    

    Which, if you ask me, is fairly pointless - I'd just stick to [[NSDate alloc] init]; for initializing objects.

    The convinience method is there so you can quickly get an autoreleased object - not to be used in conjunction with retain. It will do the same, but I would say it's better just to call the standard initialiser if you want a retained object.

提交回复
热议问题