Should I put [stock pool] in the @finally sentence?

I begin to program in Objective-C after many years of Java development. One issue I'm struggling with a bit is memory management. In particular, most examples in books and on the Internet do not seem to take into account memory leaks due to exceptions. For example, consider the following method:

-(void) doSomething  
{  
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc]init];

    // Allocate some autoreleased objects here

    NSString *data = [NSString stringWithString@"Hello"];

    // Do some work, exception could be thrown

    [PotentialExeptionThrower maybeThrowException];

    // Clean up autorelease objects

    [pool drain];
}

Should you rewrite the above to prevent memory leaks?

-(void) doSomething  
{  
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc]init];

     @try {

        // Allocate some autoreleased objects here

        NSString *data = [NSString stringWithString@"Hello"];

        // Do some work, exception could be thrown

        [PotentialExeptionThrower maybeThrowException];

    } @finally {
        // Clean up autorelease objects

        [pool drain];
    }
}

Is the code above less efficient due to @ try- @ catch ?

Thank!

+3
source share
5 answers

No, not worth it. I know that your experience has been corrupted over the years by Java, you need to change the approach to exception.

, , Cocoa. , , YOU, , . , .

, NSInvalidArgumentException - , - . !

, , , NSError. , . NSError , "" "".

- iOS : http://blog.jayway.com/2010/10/13/exceptions-and-errors-on-ios/

+1

: , . . , . ( , , , , finally .)

, , , , . , , , , , . ( . , - , , , undefined.)

+4

Apple. . , , . , , .

:

NSAutoreleasePool* A = [[NSAutoreleasePool alloc] init];
NSAutoreleasePool* B = [[NSAutoreleasePool alloc] init];

    .... do many things. Put things in B ...

NSAutoreleasePool* C = [[NSAutoreleasePool alloc] init];

    .... do many things. Put things in C ...

[A drain]; // it automatically drains B and C, too!

, . , , . , , .

+2

, Mac OS X iOS .

, undefined.

.

( - - . .)

+2

Autocomplete pools are special - normal "if you are new / alloc / copy, you must free", it does not apply exactly. When you create a resource pool, it is pushed onto a special stack. If you neglect to drain the pool, it will be drained if any pools in front of it in the stack are drained. Draining in the catch unit is not required, but an exception may delay draining the drain. Read the " Autorelease Pools Area and the Consequences of Nested Autorelease Pools " for details.

0
source

Source: https://habr.com/ru/post/1779756/


All Articles