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
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 release
d.
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