if I run this code:
NSString *xml = [[NSString alloc] init];
xml=[NSString stringWithFormat:@"<%@>", @"msg"];
NSLog(@"%@\n",xml);
[xml release];
I got:
2010-09-07 11:45:15.523 test[1312:207] <msg>
2010-09-07 11:45:15.527 test[1312:207] *** -[CFString release]: message sent to deallocated instance 0x3d52ba0
I have red the memory guide and I think that:
if i create an object using the alloc & init methods, I should release that object, but the rule does not play well here, why?
UPDATED
it seems that this line xml=[NSString stringWithFormat:@"<%@>", @"msg"]; is the problem.
I replaced it by xml=@"something"; and it worked.
any idea why I can not use the stringWithFormat method here?
UPDATED
Thanks for the answers @(Douwe Maan, BoltClock, Rod)
I have updated the code, just testing another way:
NSString *xml = [[NSString alloc] initWithFormat,@"<%@>", @"msg"];
NSLog(@"%@\n",xml);
[xml release];
interesting: if i run that code with the debug option enabled i get a message saying:
*** -[CFString _cfTypeID]: message sent to deallocated instance 0x3954ab0
but if i run it without the debugging tool, it never sends a message saying that.
questions:
1. is it normal that the error message will not appear if i am not running the project with the debug tool?
2. so, what is the problem with initWithFormat?, is it the same that has stringWithFormat? (i think it does not create an autoreleased instance)
3. how may i know that some method returns an autoreleased instance?, is there some naming convention anywhere?
Both
@"some string"(apparently not, read @BoltClock’s second comment) and[NSString stringWithFormat:@"some string with object: %@", someObject]return anautoreleased instance ofNSString. You can use this object any way you like, but you don’t own it (since you didn’talloc,copyorretainit), so you don’t have to and shouldn’treleaseit yourself.Also, in your code, you actually have two
NSStringobjects, the one youalloc‘d (on line 1) and the one that isalloc‘ed for you when you callstringWithFormat:, on line 2. On line 2 you’re re-pointing the variablexmlto the secondNSString, but the first one is still around in memory, so you’re creating a memory leak (as you haven’treleased it)! You didn’t have toallocthis first one anyway, as your secondNSStringis the only one you’re actually using.So the correct code would be, getting rid of the
releasecall and the firstNSString:Questions:
init...should be called afteralloc‘ing something, so it’s always[[Object alloc] initWithSomething]. The autorelease-version of this is[Object objectWithSomething], which does essentially this:return [[[Object alloc] initWithSomething] autorelease].alloc,copyorretain, and you do not own everything else.