The problem is that stringWithContentsOfURL
can return an autoreleased object. But you could use
initWithContentsOfURL
instead:
NSArray *urls = <# An array of file URLs #>;
for (NSURL *url in urls) {
NSError *error;
NSString *fileContents = [[NSString alloc] initWithContentsOfURL:url
encoding:NSUTF8StringEncoding error:&error];
/* Process the string ... */
fileContents = nil;
}
init...
methods return a (+1) retained object and not an autoreleased object, therefore
fileContents = nil
releases the object and destroys it (if there are no other
strong references to it).
Of course this would help only if the "string processing code" does not produce
other autoreleased objects. (Also error
, if set, would be an autoreleased
object.)
(Actually it not "guaranteed" that stringWithContentsOfURL
returns an autoreleased
object. Especially in Release mode, the ARC compiler removes many unnecessary
retain/autorelease/release operations.)
I don't know if establishing a local autorelease pool is an expensive operation or not (I assume not). If you process many objects in the loop and you don't know exactly whether autoreleased objects are created or not, it might be sensible to just use the local autorelease pool and "don't care about it". Profiling with "Instruments" could also give more insight.
For more information, see "Retained return values" and "Unretained return values" in the Clang ARC documentation.