2

The following code should crash under "Manual reference count" since the objects inside the array are getting released twice. Why does it not crash?

NSMutableArray *array = [NSMutableArray array];
[array addObject:@"1"];
[array addObject:@"2"];
[array addObject:@"3"];


for (int i=array.count-1 ; i>= 0 ; i--)
{
    id object = [array objectAtIndex:i];
    [object release];
    [array removeObject:object];
}
aryaxt
  • 76,198
  • 92
  • 293
  • 442
  • Only call `release` if you own the object (called `alloc`, `retain`, `copy`, or `mutableCopy`). You don't own the objects in the array so you must not release them. – rmaddy Jan 22 '14 at 19:31
  • @rmaddy I know that, my question wasn't why it crashes. It was why it doesn't – aryaxt Jan 23 '14 at 05:48

1 Answers1

5

Why does it not crash?

Because the objects in question are object literals, which are treated somewhat differently. Basically, such objects are never deallocated. See Objective C NSString* property retain count oddity for a full explanation.

If you change the second line like this:

[array addObject:[stringWithFormat:@"1"]];

you should see the crash that you're expecting because the first item in the array will be not be a string constant, but rather a regular old dynamically allocated string subject to the usual reference counting rules.

Community
  • 1
  • 1
Caleb
  • 124,013
  • 19
  • 183
  • 272
  • For additional details, see the NSString section of https://www.mikeash.com/pyblog/friday-qa-2012-06-22-objective-c-literals.html – BergQuester Jan 22 '14 at 18:30
  • Same result with NSDictionary being added to array – aryaxt Jan 22 '14 at 18:31
  • http://stackoverflow.com/questions/6069459/does-some-text-give-an-autoreleased-or-retain-1-object-back – BergQuester Jan 22 '14 at 18:32
  • @aryaxt Was it a dictionary of the form `@{@"foo" : @"bar"}`? In other words, was it an [object literal](http://clang.llvm.org/docs/ObjectiveCLiterals.html)? I changed the wording in my answer to cover all object literals, not just strings. – Caleb Jan 22 '14 at 18:36
  • No NSSidctionary dictionaryWithKeyAndValues:, finally got it to crash I'm happy now. Your solution wouldn't crash when I initialized all objects with 1, when I changed the numbers it crashes. Very weird. – aryaxt Jan 22 '14 at 18:46
  • Note that it's not impossible for `[NSString stringWithFormat:@"1"]` to be optimized to a single constant string object. If you want to guarantee a unique object for tests you should create a new mutable object like NSMutableString or NSMutableArray. – Greg Parker Jan 22 '14 at 20:30