问题
Instruments leaks says that this code leaks:
NSString *name = [file substringToIndex:i];
Layer *actualLayer = nil;
for (Layer *lay in layers) {
if ([lay.layerName isEqual:name]) {
actualLayer = lay;
}
}
name is the leaking object. There are some strange things: it only leaks sometimes, not always (this snippet of code is executed hundreds of time during a normal execution of my app, but it leaks just 3-4 times). The other strange thing is that i suppose the name object to be an autoreleasing object and it is never explicitaly retained or released, so how could it be that it's leaked?
Taking a look at the stack, substringWithRange is called by substringToIndex, so the problem I think it's in the substringToIndex method.
回答1:
Leaks occasionally reports false positives. The code you've posted looks fine, so check whether the surrounding code might be causing an issue. Particularly, use Build & Analyze which can pick up many memory management bugs. If you can't find the problem, there's a chance that it doesn't exist (in this particular case using this particular tool).
Bill Bumgarner describes another debugging tactic, using the heapshot instrument which can succeed where leaks fails.
回答2:
While the code you supplied above shows no leak, if leaks is saying that a leak occurred on this line:
actualLayer = lay;
Then look at any place before where actualLayer is being assigned, being retained, copied, etc. Leaks isn't a magical "here's exactly where you need to fix things" 99% of the time. It's more "this is where I discovered you leaked, remember, the leak happened sometime before this point."
来源:https://stackoverflow.com/questions/3953519/iphone-substringtoindex-substringfromindex-substringwithrange-memory-leak