Robert
Robert

Reputation: 38213

Objective C memory management question with NSArray

I am loading an array with floats like this:

NSArray *arr= [NSArray arrayWithObjects:
                [NSNumber numberWithFloat:1.9],
                [NSNumber numberWithFloat:1.7],
                [NSNumber numberWithFloat:1.6],
                [NSNumber numberWithFloat:1.9],nil];

Now I know this is the correct way of doing it, however I am confused by the retail counts.

  1. Each Object is created by the [NSNumber numberWithFloat:] method. This gives the object a retain count of 1 dosnt it? - otherwise the object would be reclaimed

  2. The arrayWithObjects: method sends a retain message to each object.

This means each object has a retain cont of 2. When the array is de-allocated each object is released leaving them with a retain count of 1.

What have I missed?

Upvotes: 0

Views: 446

Answers (2)

Neilvert Noval
Neilvert Noval

Reputation: 1695

There is no need to release those objects.
The arrayWithObjects: and numberWithFloat: creates object you do not own.

Upvotes: 2

John Parker
John Parker

Reputation: 54445

The NSNumber numberWithFloat: method isn't returning a retained object.

In general unless you're using alloc, copy or new you can presume that you're getting a object that has a retain count of zero. As such the only retain that's taking place is when the NSArray has the objects added to it.

There's a good blog about such things over at: http://interfacelab.com/objective-c-memory-management-for-lazy-people/

Upvotes: 6

Related Questions