Sometimes NSString becomes Invalid? - iphone

In my own iPhone Application I have used a number of nsstring variables to store values. But sometimes its value becomes Invalid! Does anybody know what may be the reason? Or tell me about the situation when a nsstring variable becomes Invalid?

NSStrings are also objects. They go by the same memory management rules. If you sin against those rules you will get a pointer to invalid memory and it will look like "invalid" data.
For example:
myString = [NSString stringWithString:#"foo"];
This will create an NSString* that's got autorelease on. When you're assigning it to an ivar that autorelease pool will soon pop putting the retain count back to 0 and dealloc'ing it while you still have a reference to it!
Naughty.
Instead, either retain it or use:
myString = [[NSString alloc] initWithString:#""];
This returns an owning reference. Remember to [myString release]; in dealloc.
This is just one example/case of bad memory management. Read the docs on how to properly manage your object lifecycle. Really.

They are being autoreleased. If you create a string using a convenience method (stringWithString, stringWithFormat) it will be added to the autorelease pool.
To stop it being released automatically, sent it a retain message and a release message when you have finished using it so that the memory is released. You can also set up properties to do this semi automatically when you assign the string to a member variable
There are a lot of articles on iPhone (and Mac) memory management here on SO and on the interwebs. Google for autorelease.

If this is for a device with fairly limited resources such as the iPhone, you should use [[NSString alloc] init*] over the static convenience methods, as you will put less pressure on the autorelease pool and lower your memory usage. The pool is drained every message loop, so the less objects to enumerate the better.
You should also be aware that autorelease objects in a loop will generate a lot of garbage unless you manage a local autorelease pool.

did you copy or retain the NSString ?

I asked the same question. And the following answer was the best of convenience. Just use:
[myString retain];
And then in dealloc method (e.g. viewDidUnload):
[myString release];

Related

EXEC_BAD_ACCESS when i try to release a NSString that has an address allocated to it

I have a NSString that i try to release.
The problem is that in some cases i get EXC_BAD_ACCESS when i try to release it. The NSString has a address allocated to it (I can see in the bottom page that it has allocated memory at 0xABCDEF).
How can avoid this problem while realeasing when there is something there ?
You can release an object, but the pointer to it can still have a value. It's just that it's a garbage value (i.e. a dangling pointer).
That's why you see a lot of code such as:
[myObject release];
myObject nil;
which first releases the object and then sets the pointer to nil. That way any message sent to it will fail silently (because it's safe to send messages to nil objects in Objective-C) rather than crashing, as seems to be happening with your app.
Since you are checking the pointer, I suspect that you are doing something weird with memory management. Don't. Just follow the Memory Management Rules and only release the objects you own.
You've likely called [release] on an already released string. How are you allocating it? When an object is released, or autoreleased, it is not automatically set to nil (0x0).
[[NSString alloc] initWithSomething] requires a release call.
[NSString stringWithSomething] does not, as by convention, it is autoreleased.

iPhone: using retain vs autorelease

Which one of these is better practice?
A) retain and release the object myself later
NSMutableArray* array = [[self getArray] retain];
....
[array release];
B) autorelease from the function returning the object
getArray {
NSMutableArray* returnedArray = [[[NSMutableArray alloc] init] autorelease];
.....
return returnedArray;
}
The simplest rule of thumb when it comes to memory management in Objective-C is that you should release anything that you've explicitly allocated (alloc), copied (copy), newed up (new), or retained (retain).
The release should be done within the scope of the aforementioned actions. If you allocate space for an object that is returned by a method, you should autorelease it before returning it. So, given the two options you've provided, B is the recommended practice.
You could read and follow Apples guidelines on memory management and performance.
Personally I think the reasons for choosing one way over the other:
Using Autorelease pros:
You can't stuff it up, memory will be freed at some point. That I like to think of as "falling into the pit of success".
cons:
Using autorelease a lot may cause you memory problems as lots of objects build up awaiting be released by the autorelease pools.
Using retain/release pros:
More control when your memory is used/freed.
On ios apple recommends that you use release instead of autorelease whenever possible to keep the size of the pool small.
cons:
Like C/C++ malloc/free new/delete you have to be careful to keep them matched up and it is easy to stuff that up, causing memory leaks.
For member variables you have no choice, retain/release is it.
I think, whichever style you choose comes down to the situation your code is in and choosing the best style based on there pro's and con's. I don't think there is any one answer to this.
If you want to return an object you have to use the second approach. In all cases where possible you should use the retain-release approach because this uses less memory.
If you new, alloc init, retain, or copy (NARC) an object, you have to release it.
When the name of a method starts with any of those words, it means it's being created for the caller, who has the responsibility to release the object when he is done with it.
Otherwise the method returned is not owned by the caller, and he has to indicate he wants to keep it calling retain on the object.
If you can choose, don't abuse autorelease when memory is a concern.
Some comments:
The first rule logically results in the second. Example: if the outcome of a function (the returned object) survives the execution of the function, all the function can do is autorelease the object.
Unless there is a memory/performance concern, the overhead of automatic memory management is better than the memory leak chances plus the increased developing time.
Try to retain/release symmetrically. Example: if you retained on init, then release on dealloc. Same for viewDidLoad/viewDidUnload.
If you use #property(retain) you have to release in dealloc.
Example:
// created with autoreleased, just call retain if you intend to keep it
NSString *orange = [NSString stringWithString:#"orange"];
// created for the caller, you'll have to release it when you are done
NSObject *apple = [NSString initWithString:#"apple"];

releasing variables to save memory

I have a beginner's question about releasing variables and not wasting memory...
I don't quite understand when to release variables. I understand that I should always do this if I have assigned them in my header file (in my #interface section and my #property commands). I release them in my -(void)dealloc function.
However, what am I supposed to do with variables that I happen to use in some of my methods, e.g.:
for (int temp = 0; temp < 3; temp++) {
// do something...
}
[temp release];
This is obviously wrong (at least xCode tells me so), as 'temp' is undeclared. But why? I've declared it as an int and temp thus takes up space in my memory, I'm sure. How do I tell the program to free up the space temp has taken after I don't need it anymore? I'm sure this is obvious, but I simply don't get it.
I'd be very happy for any suggestions for a beginner of how not to be a memory pig and to have 'memory leaking' everywhere in my apps...
You declared it as an int in the scope of the loop. Once the loop is done, it goes out of scope.
Also, you can not release an int, which is a primitive type. You can only release a subclass of NSObject. A good rule of thumb is that you eventually have to release anything that you called alloc or retain on.
Edit: For your edification, memory management only applies to objects allocated from the heap. That would be NSObjects obtained via "alloc" or must C-level memory allocated with something like "malloc()". Declaring a variable like "int x" is called an "auto" variable in that is is created on the stack and will AUTOmatically disappear then that block ends (the end of a "block" being the end of the function or perhaps the end of a {} pair or even the end of a for/if/while block.
Since Objective-C is basically just a special version of C (with messages), it does not create permanent objects unless you explicitly tell it to. This is different form languages like Python or Javascript.
You only need to release objects, and temp is an int, not an object.
As far as when to release objects, Apple's docs explain that better than I can: http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/MemoryMgmt/MemoryMgmt.html
You do only release objects, and not primitive types. For example you create an array with
NSArray *myArray = [[NSArray alloc] init];
This initialization allocated memory which you have to free after your done using your array, it's your responsibility, else there will be memory leaks. You can do that in the dealloc section of a controller, or at the end of a method, or even after you've enumerated through the array and no longer need it.
If you create instances of objects with other methods than alloc, copy or new(rarely used) you have to release them. If you call retain yourself on an object you have to release it as well.
Please refer to apples memory management rules, which have been posted earlier.
There are two ways to store information in RAM in C and c like things, primitives which are allocated automatically by the compiler, and memory chunks allocated by you in your program.
Variables allocated for you by the compiler are called "automatics" and can be marked by the essentially unused (because it is the default) "auto" keyword. Automatics are bound to the scope in which they are declared and go away when it ends. Regular variables, like "int x" are automatic.
Notably, pointers are typically automatic. However, the things they point to are not. Those would be the thing you asked to be allocated.
In objective-c, things are allocated with the alloc message. However, sometimes a class will call this for you, so you might not see it. To help make it clear what you should do, there is a tradition: If you get an object where you alloc'ed it, got it from a class method with the word "copy" in the method name, or sent it a "retain" message, then you own a share of it, and it won't go away until you send it a release message.
If you didn't get the object through one of those means, you must not release it, because you don't have a share in it.
So, in summary: regular variables (int, short, char, double, float, long) are automatic, no need to allocate it. Pointers are also automatic, however, the things they are pointing to are not. In obj-c, you own a share if you alloc'ed it, copy'ed it, or sent it a retain message.
You can't release an integer...
Release works only with instance of Objective-C classes.
Variables such as integers are placed on the stack, and they does not persist after a function/method call, unless allocated explicitely.
You only release objects. If you use the alloc, init procedure to create an object you must release it. If you retain an object you must release it. If you use a method that has the word "create" in it, you must release it. Anything else, the system will handle for you.
Primitives do not need to be released, only objects.
Biggest thing to keep in mind is that whenever you "alloc" or "retain" an object, put a corresponding "release" or "autorelease".
you see an error on the line [temp release]; because temp is not in scope. temp will not be seen outside of the for loop you created.
you do not need to clean up the memory of temp, since you have not claimed ownership of it(see Memory Management Rules): http://developer.apple.com/library/ios/#documentation/general/conceptual/DevPedia-CocoaCore/MemoryManagement.html
examples of objects where you do not need to release/manage memory:
NSArray *myArray = [NSArray array];
NSNumber *myNumber = [NSNumber numberWithInt:5];
NSString *myString = #"Hello World";
NSInteger i = 5;
int x = 2;
examples of objects where you do need to release/manage memory:
NSArray *myArray = [[NSArray alloc] initWithObjects:#"Hello", #"World", nil];
NSNumber *myNumber = [[NSNumber alloc] initWithInt:5];
NSString *myString = [[NSString alloc] initWithString:#"Hello World"];
-
typically, when your completely done using an object you own, you clean up its memory
see apple's docs for explanations on properties: http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjectiveC/Chapters/ocProperties.html#//apple_ref/doc/uid/TP30001163-CH17-SW1
setting a property with assign or readonly: you should not worry about releasing its memory, as you don't own it
property with retain or copy: you claim ownership of the object and need to release it at some point
this answer won't answer/solve all memory management questions/concerns, but it may shove you in the right direction

What's the recommended approach for allocating an object in an instance methode, which will later on be returned?

For example look at the following example:
Code1
-(NSString*)getString{
return [[[NSString alloc] initWithFormat:#"test"] autorelease];
}
-(void)printTestString{
NSString *testStr = self.getString;
[testStr retain]
NSLog(#"%#",testStr);
[testStr release]
}
Code2
-(NSString*)getString{
return [[NSString alloc] initWithFormat:#"test"];
}
-(void)printTestString{
NSString *testStr = self.getString;
NSLog(#"%#",testStr);
[testStr release];
}
Code 1 and Code 2 should be valid Code Snippets and no leaks should appear.
Code 1 uses autorelease so the return variable has to be retained in printTestString and after using it released. So there is a small Overhead here because of autorelease.
Code 2 doesn't release the NSString in getString so you have to only release it after using it. Seems your have to write less and you dont have overhead because no autorelease is used.
Which one is the de facto "standard" approach that is used out there?
Another thing I was asking myself. Could the autorelease in getString and the retain with
[testStr retain]
be a problem, when the autorelease pool releases the variable right after
NSString *testStr = self.getString;
then the string would be gone. Is that possible or does the compiler prevent that sort of thing?
Thanks
-Sebo
Do this:
-(NSString*)getString{
return [[[NSString alloc] initWithFormat:#"test"] autorelease];
}
-(void)printTestString{
NSString *testStr = self.getString;
NSLog(#"%#",testStr);
}
Your getString method autoreleases the NSString, which means printTestString doesn't need to retain or release it. Autoreleasing in getString makes sense, because it alloced the object and is therefore the 'owner' of the object. I suggest studying Objective-C's memory management rules before proceeding, as they are very important.
http://developer.apple.com/library/mac/#documentation/cocoa/conceptual/MemoryMgmt/Articles/mmRules.html#//apple_ref/doc/uid/20000994-BAJHFBGH
Jake's answer is correct for almost all of the situations you'll need to return an object from a method, but there are cases where you might want to return something that isn't autoreleased. From the Memory Management Programming Guide (Mac version, but they're the same rules):
You take ownership of an object if you
create it using a method whose name
begins with “alloc” or “new” or
contains “copy” (for example, alloc,
newObject, or mutableCopy), or if you
send it a retain message.
Also, from the Coding Guidelines for Cocoa:
In your methods and functions that
return object values, make sure that
you return these values autoreleased
unless they are object-creation or
object-copy methods (new, alloc, copy
and their variants). “Autoreleased” in
this context does not necessarily mean
the object has to be explicitly
autoreleased—that is, sending
autorelease to the object just before
returning it. In a general sense, it
simply means the return value is not
freed by the caller.
For performance reasons, it’s
advisable to avoid autoreleasing
objects in method implementations
whenever you can, especially with code
that might be executed frequently
within a short period; an example of
such code would be a loop with unknown
and potentially high loop count.
Therefore, methods containing the prefix alloc or new, or those that contain the word copy by convention will have you returning objects that are not autoreleased. In fact, the Clang Static Analyzer understands this convention and will assume non-autoreleased objects being returned from methods that follow these naming rules.
I've used the new prefix in situations where I preferred not to return autoreleased objects (tight loops where I didn't want to manage an autorelease pool, etc.). Again, returning autoreleased objects is what's recommended in almost all cases, but there are some times where you might want to avoid that.

Mem management for returned local variable

I am a little confused about retain/release count when a local variable is allocated within a method, then returned to its caller. For example
-(NSMutableString*)foo {
NSMutableString *str = [[[NSMutableString alloc] init] autorelease];
[str appendString:#"Just a test"];
return str;
}
NSMutableString *myString = [self foo];
Questions: (as you can see I am quite confused by this case)
1. Will str retain count increment when it is assigned to myString?
2. Is it safe to autorelease in this case?
3. Who should clean up the memory?
Thanks.
I would suggest you read the Cocoa memory management guidelines. All your questions are answered in there.
To answer about this particular code example: It's managing memory properly. This is what autorelease is for — where you need an object to stick around past a particular method invocation but still get released. You essentially turn ownership over to the autorelease pool.
And there's no magic to retaining and releasing. Assigning a local variable won't affect an object's retain count — it has to be sent retain or release for that to happen.
There's no special magic involved.
When a retain message is sent to an object, its retain count increases.
When a release message is sent to an object, its retain count decreases.
When an autorelease message is sent to an object, it adds itself to a pool.
When the pool is drained (which may be at the end of a run loop or thread), anything in that pool gets sent a release message.
When an object receives as many release messages as it has retain messages (assuming there's an implicit retain caused by alloc), the object sends itself a dealloc message.
The retain count of an object is otherwise untouched (barring any optimisations).
1) No
2) Yes - that's the correct pattern for this case. (You don't want callers to have to track and release this NSMutableString instance)
NSMutableString *str = [[NSMutableString alloc] init];
return str;
Would be bad because your caller is now forced to manage the returned variable.