Re: verify input parameter of init method and return nil before invoke [super init]
Re: verify input parameter of init method and return nil before invoke [super init]
- Subject: Re: verify input parameter of init method and return nil before invoke [super init]
- From: Ken Thomases <email@hidden>
- Date: Tue, 29 Jan 2013 22:51:05 -0600
On Jan 29, 2013, at 3:22 AM, Quincey Morris wrote:
> On Jan 29, 2013, at 00:51 , Bob Cromwell <email@hidden> wrote:
>
>> if below code valid ? All sample codes I could find invoke "self = [super init]" first and then check the input parameter inside "if (self)" block.
>>
>> @implementaion Bla
>>
>> - (id)initWithFoo:(NSString *)foo
>> {
>> if (foo == nil) {
>> return nil;
>> }
>> self = [super init];
>> if (self) {
>> _foo = foo;
>> .....
>> }
>> return self;
>> }
>>
>> I had thought there would be memory leak. "Bla * b = [Bla alloc ] initWithFoo:nil];" . However under ARC using Instruments Leaks, there are no leak found.
>
> No, it's not valid. You can see why if you rewrite this using manual retain/release conventions:
>
> if (foo == nil) {
> [self release];
> return nil;
> }
> self = [super init];
>
> You must (and ARC does) release 'self' before returning nil, to avoid a memory leak. The problem is that releasing 'self' will invoke 'dealloc', and you have no idea whether it's safe to invoke 'dealloc' if you haven't invoked done '[super init]' yet.
I disagree. I think Bob's construction is valid, if unconventional. It is also valid-though-unconventional to release an object that you've +alloc'd but not -init'd at the caller side.
SomeClass* foo = [SomeClass alloc];
if (someCondition)
{
[foo release];
return;
}
foo = [foo init];
Bob's construction is just as valid as the above because it's essentially doing the same thing.
You're right to argue that, in practical terms, some classes may have -dealloc implementations that fail in these circumstances, but then those -dealloc implementations are buggy.
Regards,
Ken
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden