0

What is the difference between

NSMutableArray* p = [[NSMutableArray alloc] initWithObjects:...]

and

NSMutableArray* p = [NSMutableArray arrayWithObjects:...]

4 Answers 4

6

In the first one, you have the ownership of array object & you have to release them.

NSMutableArray* p = [[NSMutableArray alloc] initWithObjects:...];
[p release];

& last one you dont need to release as you don't have the ownership of array object.

NSMutableArray* p = [NSMutableArray arrayWithObjects:...]; //this is autoreleased

If you call release in this, then it will crash your application.

Sign up to request clarification or add additional context in comments.

2 Comments

Isn't arrayWithObjects autoreleased by default?
yes this is autorelease...we don't need to call autorelease. Thanks for editing fzwo :)
3

[NSMutableArray arrayWithObjects:] is the same as [[[NSMutableArray alloc] initWithObjects:] autorelease]

3 Comments

so, which is the better way? To alloc and release manually or to alloc with "autorelease"?
@ZhaoRocky In practice, the best way is to use ARC. If you can't use ARC, read up on manual reference counting. Neither manual retain/release nor autorelease are inherently better, it depends entirely on the situation.
Indeed. If one way was just "better" in all situations, the other one wouldn't exist.
2

In practice, there is no difference if you're on ARC.

The latter basically is just a shorthand for [[NSMutableArray alloc] initWithObjects: ...], except the returned array is autoreleased (which is important if you're still doing manual reference counting).

2 Comments

Not quite. The latter autoreleases the return value.
Right. In practice, on ARC, there is no difference. Thanks for pointing that out, though. I'll edit my answer.
0

What I think the difference is that: initWithObjects is a instance method, and arrayWithObject is a class method.

1 Comment

While that is certainly true, it's also completely irrelevant :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.