Xcode leaks tool does not identify property leaks
I have this simple code
@interface chatApp4Message : NSObject {
NSString* li开发者_JS百科ne;
}
@property (nonatomic, retain) NSString* line;
@end
@implementation chatApp4Message
@synthesize line;
@end
As you can see, I don't release the line property. However, when running this following simple code under the Xcode leaks tool, I get no indication of memory leaks
for (int i=1; i< 100; i++){
chatApp4Message* msg = [[chatApp4Message alloc] init];
msg.line = @"aaaaaa";
[msg release]
}
Actually there's no memory leaks in your code. @"aaaaaa" is a string literal object and is created at compile time and it persists all the time your application runs. However change your code to really create string object and you'll get memory leak:
for (int i=1; i< 100; i++){
chatApp4Message* msg = [[chatApp4Message alloc] init];
msg.line = [NSString stringWithFormat:@"%d", i]; // It leaks!
[msg release]
}
P.S. May be this discussion on string literals will be useful...
Your code is technically leaking for the reasons you think, but Instruments is measuring reality, not theory. If you were to run the static analyzer on your code (Build & Analyze), it should detect the leak.
String literals --
@"...."
-- are actual compiled static NSString instances. At runtime,[@"foo" class]
would indicate that the string is an instance ofNSCFConstantString
(IIRC -- some constant string class anyway) that does nothing onretain
,release
, orautorelease
, because it isn't actually an allocated instance.If you want to play with Leaks analysis, do so with mutable strings or with instances of some class you create.
I often use a function like the following to generate mutable self-identifying string instances to futz with leaks or object graph analysis:
NSString *testString(NSString *prefix) {
NSMutableString *s = [NSMutableString stringWithString: prefix];
[s appendFormat: @" (%p)", s];
return s;
}
精彩评论