Initializing objects [duplicate]

2019-09-08 06:05发布

问题:

Possible Duplicate:
Diference between [NSMutableArray array] vs [[NSMutableArray alloc] init]

Using Objective-C/Cocoa, what's the difference between:

NSMutableData *myData = [NSMutableData data];
NSMutableString *myString = [NSMutableString string];

and

NSMutableData *myData = [[NSMutableData alloc] init];
NSMutableString *myString = [[NSMutableString alloc] init];

They seem to have the same end result as far as I can tell?

回答1:

[NSMutableData data] is referred to as a helper, check this post, Helper functions in Cocoa

Helpers generally take care of the memory management for your, can also be used to return singletons.

[[NSMutableData] alloc] init], you are responsible for memory management.

Although if you are using ARC you don't have to release your objects, it does it for you.