Difference between NSString literals

后端 未结 5 770
难免孤独
难免孤独 2020-11-27 06:46

What is the difference between these two lines?

NSString * string = @\"My String\";
NSString * string = [[[NSString alloc] initWithString:@\"MyString\"] auto         


        
5条回答
  •  一生所求
    2020-11-27 07:23

    Just remember this basic thing:-

    NSString *string = ...
    

    This is a pointer to an object, "not an object"!

    Therefore, the statement: NSString *string = @"Hello"; assigns the address of @"Hello" object to the pointer string.

    @"Hello" is interpreted as a constant string by the compiler and the compiler itself allocates the memory for it.

    Similarly, the statment

    NSObject *myObject = somethingElse;
    

    assigns the address of somethingElse to pointer myObject, and that somethingElse should already be allocated ad initialised.

    Therefore, the statement: NSObject *myObject = [[NSObject alloc] init]; allocates and initializes a NSObject object and assigns its address to myObject.

提交回复
热议问题