As Bill said, Id will first try to create an autostart pool for each iteration of the loop, for example:
for (NSString *part in partsOfLargeString) { NSAutoreleasePool *pool = [NSAutoreleasePool new]; NSString *trimmedPart = [part stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; NSData *data = [trimmedPart dataUsingEncoding:NSUTF8StringEncoding]; … [pool drain]; }
or, if you use a fairly recent compiler:
for (NSString *part in partsOfLargeString) { @autoreleasepool { NSString *trimmedPart = [part stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; NSData *data = [trimmedPart dataUsingEncoding:NSUTF8StringEncoding]; … } }
If this is still unacceptable and you need to unlock the objects in more detail, you can use something like:
static inline __attribute__((ns_returns_retained)) id BICreateDrainedPoolObject(id (^expression)(void)) { NSAutoreleasePool *pool = [NSAutoreleasePool new]; id object = expression(); [object retain]; [pool drain]; return object; } #define BIOBJ(expression) BICreateDrainedPoolObject(^{return (expression);})
which evaluates the expression, saves its result, frees any auxiliary objects with auto-implementation and returns the result; and then:
for (NSString *part in partsOfLargeString) { NSAutoreleasePool *pool = [NSAutoreleasePool new]; NSString *trimmedPart = BIOBJ([part stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]); NSData *data = BIOBJ([trimmedPart dataUsingEncoding:NSUTF8StringEncoding]); [trimmedPart release];
Please note: since the function returns a stored object, you are responsible for freeing it. When you do this, you will have control.
Feel free to choose the best names for function and macro. There may be some corner cases that should be handled, but they should work for your specific example. Suggestions are welcome!
user557219
source share