开发者

memory leaks in my strings

I have this in my code :

NSString *myString = @"";
....

if (...) {
mySt开发者_如何转开发ring = @" other string";
}
...
myString = @" an other string ";

is this a leak, please ?


Sorry, guys, but it's not autoreleased. It's not leaked, but it's not autoreleased. This code prove it:

NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSString *str1 = @"First one"; // 
NSString *str2 = [NSString stringWithFormat:@"The %dnd", 2]; // this autoreleasing string
[pool drain];

NSLog(@"%@", str1); // All's ok
NSLog(@"%@", str2); // EXC_BAD_ACCESS

Read about strings created with @"..." construction at Strings PRogramming Guide:

The compiler makes such object constants unique on a per-module basis, and they’re never deallocated, though you can retain and release them as you do any other object.


No this is not a leak it will be autorelease


It is not a leak. You leak memory only when you allocate memory and don't release the memory.

In your case what ever you have created is an auto released object. They will be released at a later time.


You leak memory when you take ownership of the object by allocating them using alloc init or new , retain or mutablecopy methods and subsequently not release them. Then it causes a leak. Take a look at Object Ownership

You own any object you create.

You “create” an object using a method whose name begins with “alloc”, “new”, “copy”, or “mutableCopy” (for example, alloc, newObject, or mutableCopy).

You can take ownership of an object using retain.

Remember that an object may have more than one owner. Taking ownership of an object is your way of saying that you need it to be kept alive. (This is discussed in more detail in “Accessor Methods.”)

You must relinquish ownership of objects you own when you’re finished with them.

You relinquish ownership of an object by sending it a release message or an autorelease message (autorelease is discussed in more detail in “Autorelease”). In Cocoa terminology, relinquishing ownership of an object is therefore typically referred to as “releasing” an object.

You must not relinquish ownership of an object you do not own.

This is primarily an implicit corollary of the previous policy rules, made explicit.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜