Why in Objective-C does doing alloc and init in separate statements cause the object to be released according to the Xcode static analyzer?

前端 未结 3 1679
半阙折子戏
半阙折子戏 2021-01-06 11:00

I\'m making my first steps with Objective-C and have encountered a minor, albeit confusing issue with the static analyzer (Product->Analyze) in XCode 4.1. I have created a

3条回答
  •  我在风中等你
    2021-01-06 11:33

    Trying to separate calls to +alloc and -init is explicitly recommended against by Apple, per the documentation for +[NSObject alloc]:

    An init... method must be used to complete the initialization process. For example:

    TheClass *newObject = [[TheClass alloc] init];

    and -[NSObject init]:

    In some cases, an init method might release the new object and return a substitute. Programs should therefore always use the object returned by init, and not necessarily the one returned by alloc or allocWithZone:, in subsequent code.

    The static analyzer is complaining because it expects that +alloc will be paired with -init. Because -init can release the sender, the static analyzer therefore thinks you're trying to call a method on a deallocated instance.

提交回复
热议问题