brianSan
brianSan

Reputation: 535

Objective-C: What is the difference between creating an object from alloc/init and class method calls?

For example,

  1. NSString *string = [NSString stringWithString:@"a string"];
    
  2. NSString *string = [[NSString alloc] initWithString:@"a string"];
    

and while we're talking about strings, is there any difference by setting up a string with:

    NSString *string = @"a string";

?

As a final note, this isn't a specific question about NSString. I'm asking on a wider scope of all NSObjects.

Upvotes: 3

Views: 209

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727067

There is no difference in ARC, but prior to it there was a difference: alloc/init returns an item with ref count of at least one that you'd need to release when you don't need it, while the class method returns an autoreleased item that you'd need to retain if you would like to keep it. The ARC compiler knows all this, and takes care of retaining/releasing for you based on your ownership specifications.

Upvotes: 4

Related Questions