Why should I not separate alloc and init?

后端 未结 4 1210
醉梦人生
醉梦人生 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:38

    As per my understanding an allocated object makes no sense without it being initialized,

    if you alloc an object first and then later plan to initialize it, there might be a case that you may forget to initialize the object and give a direct call to any of its instance method which would result in run time error.

    Example:

        NSString *str = [NSString alloc];
    // Override point for customization after application launch.
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    NSLog(@"%ld",str.length);
    

    When i run the above code i get this in my console

    Did you forget to nest alloc and init?
     *** Terminating app due to uncaught exception 'NSInvalidArgumentException', 
    reason: '*** -length only defined for abstract class.  Define -[NSPlaceholderString length]!'
    

    if i would do the below I would still get the exception as str is not being initialized because whatever is being initialized is not being consumed or pointed by str

    [str init];
    

    Hence if you want to do it in two lines it should be like this

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

    But it's always better to keep them nested

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

    If you plan on doing it on single line then use the new keyword which servers the purpose of allocation and initialization on a single line.

    Example: YourClass *object_ofClass = [YourClass new];

提交回复
热议问题