Luca
Luca

Reputation: 20919

releasing object after return, is it good practice?

i am just wondering if we can do so:

 SBJsonParser *parser = [[SBJsonParser alloc] init];
    id repr = [parser objectWithString:self];

    return repr;
    [parser release];

So releasing object after returning it, is this a good practice? thanx for any information :)

Upvotes: 0

Views: 266

Answers (6)

janusfidel
janusfidel

Reputation: 8106

A method returns to the code that invoked it when it

  • completes all the statements in the method

  • reaches a return statement

  • or throws an exception.

Upvotes: 0

Tharabas
Tharabas

Reputation: 3422

Simple answer: NO

You can not execute anything after a return statement.

Instead you should autorelease the object. That will deallocate it within the next cleanup run of the surrounding AutoreleasePool.

SBJsonParser *parser = [[[SBJsonParser alloc] init] autorelease];
return [parser objectWithString:self];

Upvotes: 3

calimarkus
calimarkus

Reputation: 9977

Have you learned programming basics? After a return statement, nothing is executed.

See: Why does NSLog() not do anything if it's after a method's return?

Upvotes: 0

Denis Mikhaylov
Denis Mikhaylov

Reputation: 2045

Actually your code after return statement won't even be executed. glogic's solution is the way to go.

Upvotes: 0

Vignesh
Vignesh

Reputation: 10251

You compiler will not reach the any line after the return statement(Except When you use finally statement.). You got to autorelease it.

Upvotes: 0

glogic
glogic

Reputation: 4092

SBJsonParser *parser = [[[SBJsonParser alloc] init]]autorealease];//<<< auto release the object on creaion
    id repr = [parser objectWithString:self];

    return repr;

Upvotes: 1

Related Questions