1

When I've try to Analyse .m, I've got strange warning:

warning: Object with a +0 retain count returned to caller where a +1 (owning) retain count is expected

on the line

return [NSNumber numberWithInt:1];

the code is:

- (NSNumber*)index
{
  return [NSNumber numberWithInt:1];
}

Similar code with string is passed correctly.

- (NSString*)ss
{
    return [NSString stringWithFormat:@"%d", 1];
}

Did I miss something with NSNumber constructor, or is it bug in Analyser?

Gabriele Petronella
  • 106,943
  • 21
  • 217
  • 235
Igor Pchelko
  • 308
  • 3
  • 13
  • I cannot reproduce the warning with your code. Is this your exact code? Which Xcode/SDK do you use? Naming the method `newIndex` causes that warning as expected, but not `index`. – Martin R Nov 02 '13 at 19:40

2 Answers2

1

This looks like a bug in the analyzer, because in both cases an autoreleased object is returned.

Note that you can simplify the code with the new @ syntax as follows:

- (NSNumber*)index
{
  return @1;
}

You need parentheses if you must return an expression, like this:

- (NSNumber*)index
{
  return @(value1 + value2); // Same as [NSNumber numberWithInt:value1 + value2];
}
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • 1
    return @1; - produce same warning. Looks like it's Analyser's bug. – Igor Pchelko Nov 02 '13 at 19:33
  • @IgorPchelko Yes, this definitely looks like a bug in the analyzer: `index` does not fall in the [method family](http://stackoverflow.com/a/15747674/335858) that needs to return a +1 ref count, so it should not give you the warning. – Sergey Kalinichenko Nov 02 '13 at 19:36
1

In Objective-C methods naming is critical in determining their memory management.

Methods whose name starts with alloc, new, copy or mutableCopy are expected to return an object with a +1 retain count, whereas everything else should return autoreleased objects, i.e. with a +0 retain count, as explained in the Advanced Memory Management Guide.

With this in mind, if your method is really named index then the analyzer is mistaken.


As a side note, you can take advantage of Objective-C literals for a simpler NSNumber creation.

[NSNumber numberWithInt:1]

can be replaced by

@1

and

[NSNumber numberWithInt:anExpression];

can be replaced by

@(anExpression)
Gabriele Petronella
  • 106,943
  • 21
  • 217
  • 235
  • You right. My method name starts with "new". Therefore analysers expect non autoreleased object. – Igor Pchelko Nov 03 '13 at 10:02
  • 1
    @IgorPchelko: Please do always copy/paste your actual code, to avoid that other people waste their time by trying to solve a problem that does not exist. – Martin R Nov 03 '13 at 13:23