views:

172

answers:

2

the follwing will allocate memory in RAM ....?

NSArray *obj = [[NSArray arrayWithObjects: @"Hai", @"iHow",
nil] retain];

+7  A: 

Yes. It will create an NSArray object and store it on the heap. The arrayWithObject method returns an autoreleased object, but your extra retain statement makes sure the reference count will be at least one, and the memory won't get freed until you explicitly release it.

It might be worth adding, it's not the "retain" statement that allocates the memory, the memory is allocated by the arrayWithObject method. The retain statement simply increments the reference count for that object.

Tom
what means the memory is allocated inside the arrayWithObject method
Mikhail Naimy
[[NSArray arrayWithObjects: @"Hai",@"iHow",nil] retain]; contains two method calls "arrayWithObjects" and "retain". It's the arrayWithObjects that allocates the memory, not the retain.
Tom
+4  A: 

To add to Tom's correct answer, the line:

[NSArray arrayWithObjects: ...]

is equivalent to:

[[[NSArray alloc] initWithObjects:...] autorelease]

so rather than tacking a retain onto the first line, you could just do:

[[NSArray alloc] initWithObjects:...]

In any case, the memory is allocated in alloc, whether that method appears in your code or is implicit (as it is in autoreleasing class-method convenience calls like the first one).

invalidname