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 1575
半阙折子戏
半阙折子戏 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:37

    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?

    absolutely.

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

    you would assign the value of the initialized object to f (as you have). at this point, a may be a dangling pointer (if another address is returned). thereore, f should be released.

    the explanation for this order is that the object may have opted to return a specialized version/variant of itself, and this reallocation happens along the init... chain.

    silly demonstration:

    @interface Fraction : NSObject
    {
    @private
        int numerator;
        int denominator;
    }
    
    @end
    
    static Fraction* EvilFraction = ...;
    
    @implementation Fraction
    
    - (id)initWithNumerator:(int)num denominator:(int)den
    {
        self = [super init];
        if (nil != self) {
            if (0 == den){
                [self release];
                return [EvilFraction retain];
            }
        }
        return self;
    }
    
    @end
    

提交回复
热议问题