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 1572
半阙折子戏
半阙折子戏 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:31

    So is it possible that init can return a different pointer than the one passed to it from alloc, rather than just configuring the memory it has been passed?

    Yes, that's exactly it. This is also the reason why you don't just call [super init] in your initialisers; instead you call it and assign the result to self because you aren't necessarily going to get the same instance back.

    The relevant documentation is in The Objective-C Programming Language.

    With this code should I pair [ a release ] with the alloc or [ f release ] with the init?

    If you really want to do something like that, you'd have to check that they aren't equal first, otherwise you'd be over-releasing. But the real solution is to not split up alloc and init. That's the idiomatic way of instantiating objects in Objective C and doing it a different way that you have to add extra code for is counterproductive.

提交回复
热议问题