0

I have the following (simplified) code from a generic factory class:

- (id) invokeSetup: (id) object {
    // Just an example, subclasses delegate setup to a component that either returns +0 or +1 references
    return objc_msgSend(object, @selector(init));
}

- (id) newInstance {
    id object = objc_msgSend([NSString class], @selector(alloc));
    id replacement = [self invokeSetup: object];

    return replacement;
}

The analyzer produces a warning on the return replacement::

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

I somehow need to tell the analyzer that the reference returned by - invokeSetup is +1. The above example is simplified, and in the real program, there are a few constraints:

  1. I cannot annotate invokeSetup with ns_returns_retained, since it is inherited, and there are other subclasses where invokeSetup returns +0 references. If it is a +1 or +0 can only be detected at runtime.

  2. I cannot change the name of any methods.

  3. The design is the way it is. There may be better designs, but that can't be changed here.

Is it possible to somehow tell ARC at the point of assignment (id replacement = ...) that the reference definitely is +1?

Thanks, Jochen

Jochen
  • 7,270
  • 5
  • 24
  • 32
  • I know you said this is an example but why is the factory pattern trying to reinvent/replace `alloc & init`? And why would `init` sometimes return retained? `alloc` should only be returning retained otherwise some objects on creation would have a retain count of while other 2. If it were non-ARC then it would lead to code that looked like `NSString *s = [@"test" newInstance]; [s release]; [s release];`. Although you can't change it is there anyway you can just avoid it? – Joe Apr 12 '12 at 14:59
  • 2
    Basically the constraints you are placing rule out all the possible solutions, sorry. Well I'm not sorry actually, this looks like a really bad bit of code. – JeremyP Apr 12 '12 at 15:10

1 Answers1

0

see https://stackoverflow.com/a/5833430/1313031 for a way to suppress static analyzer warnings in code

But yeah, the best thing to do would be to rename newInstance

Community
  • 1
  • 1
Jay Wardell
  • 2,230
  • 1
  • 14
  • 13
  • 2
    Actually the best thing to do would be to rewrite the code not to be so bad. He's got a method with different ownership semantics depending on which class or subclass is being used. There's no hope of being able to write a stable system with this. – JeremyP Apr 12 '12 at 15:29
  • I'm sorry. Renaming WOULD only make life worse. This is the kind of design that arc is meant to prevent. If you're stuck with this code, then either the above link or -fno-objc-arc will hide the warnings, but you'll still be stuck with this design. – Jay Wardell Apr 12 '12 at 15:45