How can I handle a possible memory leak due to an exception in Objective-C?

I have a method that selects an object and then releases it at the end. Between them, the method calls another method that can throw an exception, and the exception is likely to be caught by the method that calls my method. If this happens, the object will never be released (or will it be?). How to prevent this?

+3
source share
2 answers

You can always automatically release it before calling methods that can be selected - this way you can be sure that it will be released, otherwise an exception will be thrown.

If for some reason this is unreasonable, you can do the release in block @finally 1

A @finally , , .

, @finally @catch :

Resource *resource = [[Resource alloc] init];
@try {
    [obj someMethodThatMayThrow];
}
@finally {
    [resource release];
}
+2

-, , ,

Cocoa, . , , :

  • Cocoa, API

  • , , , undefined

Mac OS X iOS ; , , . , , , , .

, iOS ( , ). , @finally , @finally .

+2

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


All Articles