Skip to content Skip to sidebar Skip to footer

Why Update Statement Works With Initwithformat And Not With Stringwithformat?

I was having an issue with my UPDATE statement as I was telling here: Update issue with sqliteManager I found out that initWithFormat WORKS NSString *sqlStr = [[NSString alloc] ini

Solution 1:

I am guessing that it has to do with the memory management of the string, it might not have been sufficiently retained so it is getting cleaned up before for it is getting used. The difference between the two methods are defined here

Solution 2:

I have just found something interesting from this thread: How to refresh TableView Cell data during an NSTimer loop

This, I believe, is the reasoning behind..

I quote what "petergb" said:

[NSString stringWithFormat:...] returns an autoreleased object. Autoreleased objects get released after control returns from the program's code to the apple-supplied run-loop code. They are more or less a convenience so we don't have to release all the little objects that we use once or twice here and there. (For example, imagine how tedious it would be if you had to release every string you created with the @"" syntax...)

We can tell stringWithFormat: returns an autoreleased object because, by convention, methods who's names don't start with alloc or copy always return auto-released objects. Methods like this are said to "vend" an object. We can use these objects in the immediate future, but we don't "own" it (i.e. we can't count on it being there after we return control to the system.) If we want to take ownership of a vended object, we have to call [object retain] on it, and then it will be there until we explicitly call [object release] or [object autorelease], and if we don't call release or autorelease on it before we lose our reference to it by changing the variable to something else, we will leak it.

Contrast with [[NSString alloc] initWithFormat:. This method "creates" an object. We own it. Again, it will be there until we explicitly call [object release].

Post a Comment for "Why Update Statement Works With Initwithformat And Not With Stringwithformat?"