sayzlim
sayzlim

Reputation: 275

Why is the retainCount is 0 instead of 1?

Here is the code. I have tested with NSString, and it return -1. But for NSMutableArray is 0 instead.

NSMutableArray *items = [[NSMutableArray alloc] init];

for(int i=0;i<10;i++)
{
    [items addObject:[Possession randomPossession]];
}

/*for(int i=0;i<[items count];i++)
{
    NSLog(@"%@", [items objectAtIndex:i]);
}*/



//Using Fast Enumeration
/*for(items in items)
{
    NSLog(@"%@", items);
}*/


NSLog(@"%d", [items retainCount]);

I made mistake by using array in iteration. The correct one should be like this.

//Using Fast Enumeration
    for(Possession *item in items)
    {
        NSLog(@"%@", item);
    }

And the retainCount is back to normal as expected 1.

Upvotes: 0

Views: 127

Answers (1)

David Gelhar
David Gelhar

Reputation: 27900

A) You should never look at retainCount, even for debugging. It's an internal implementation detail that can provide confusing results.

B) This:

for(items in items)

is almost certainly not what you mean -- you're using the array object ("items") as the iterator too! Something like:

for(Possession *item in items) 

would make more sense.


update:

You might want to look at some of the examples in Apple's documentation on fast enumeration. You really want to have a separate variable that acts as your loop iterator. What you're doing (for(items in items)) sets items to each object in the array in turn, and when you exit the loop, items will be nil!

Upvotes: 7

Related Questions