Problem with stringByAppendingString and retain count
I need to concatenate some strings.
NSString * sportName = [[NSString alloc ]initWithString:@""];
sportName = [sportName stringByAppendingString:[someObject getString]];
// can be more stringByAppendingString
...
[sportName release];
But something strange for me give the 'build and analyze' command:
on string:
sportName = [spo开发者_StackOverflowrtName stringByAppendingString:[someObject getString]];
the error: Method returns an Objective-C object with a +0 retain count (non-owning reference)
on string:
[sportName release];
the error: Incorrect decrement of the reference count of an object that is not owned at this point by the caller
I am using it for filling my TableView and it is crashed after loading :(.
NSString * sportName = [[NSString alloc ]initWithString:@""];
sportName = [sportName stringByAppendingString:[someObject getString]];
In 2nd line you are getting a new string which is assigned back to spotName
. So the alloced string in first line is leaked. I don't understand why you need to append in an empty string. Appending to @""
is practically of no effect. And if you have some non-empty string then you can create that as autoreleased string instead of alloc. Like this:
// create an autoreleased string
NSString * sportName = @"my_string";
// this will return a new string which is also autoreleased
sportName = [sportName stringByAppendingString:[someObject getString]];
// all subsequent call to stringByAppendingString will return autoreleased string
//so no need to release spotName
And if you need to retain spotName
then you can retain that or use a property.
well, why do you need to alloc (and so retain) your string if you use it just inside a method (as it seems)...
try this:
NSString * sportName = @"";
instead of your "alloc":
and remove the release line...
You own sportName in the first place by sending alloc(or new, copy, mutableCopy, retain). Now you've got a fresh instance which you have to release later on.
stringByAppendingString returns an autoreleased string which you assign to sportName. The reference is lost and can never be released.
Look at the memory addresses:
NSString *sportName = [[NSString alloc ]initWithString:@"baa"];
NSLog(@"<%p> %@", sportName, sportName);
sportName = [sportName stringByAppendingString:@" foo"];
NSLog(@"<%p> %@", sportName, sportName);
Output:
2011-05-20 08:19:08.675 foo[1262:207] <0x3038> baa
2011-05-20 08:19:08.677 foo]1262:207] <0x4e40bd0> baa foo
sportname has been overwritten.
You can fix that by introducing a tmp or use a string literal:
NSString *sportName = @"baa";
or
...
NSString *tmp = [sportName stringByAppendingString:@" foo"];
精彩评论