Why should I not separate alloc and init?

后端 未结 4 1168
醉梦人生
醉梦人生 2021-01-22 21:05

The normal way to initialise and allocate in Objective-C is

NSObject *someObject = [[NSObject alloc] init];

Why is the following not practised

4条回答
  •  悲哀的现实
    2021-01-22 21:39

    From the Object Initialization official documentation:

    Because an init... method might return nil or an object other than the one explicitly allocated, it is dangerous to use the instance returned by alloc or allocWithZone: instead of the one returned by the initializer

    Another reason from the same document is that:

    Once an object is initialized, you should not initialize it again

    given this example:

    NSString *aStr = [[NSString alloc] initWithString:@"Foo"];
    aStr = [aStr initWithString:@"Bar"];
    

    where:

    the second initialization in this example would result in NSInvalidArgumentException being raised.

提交回复
热议问题