I have some sensitive data I want to clear directly after use. Currently, the sensitive data is in the form of NSString. NSString is in my understanding immutable, meaning that I can't really clear the data. NSMutableString seems more appropriate, though, as it is mutable and has methods like replaceCharactersInRange and deleteCharactersInRange. I have no knowledge of the implementation details so I wonder if NSMutableString would serve my purpose?
Hi, there is a hell lot of difference between nsstring and nsmtablestring. And always keep practice of using nsmutablestring when you are going to change the content of string.
ex:
NSString *aString = [nsstring stringWithString:@"asdasd"]; // autoreleased object
here you have created a string and want to add other string, then you will do:
astring = [astring stringByAppendingString:@"asdasd"]; //autoreleased object
here what happens is new autoreleased string is returned and the previous string is not get released. This will lead to memory leak(consumption) because you have lost the ownership of the first autoreleased object.
Think if you are using the second statement in a loop:
for(int i=0 ; i<1000 ; i++)
astring = [astring stringByAppendingString:@"asdasd"]; //autoreleased object
Then you are leaking the memory even though you cant see it.
If you used NSMutableString instead of NSString then you never come across this type of situation and you can avoid the leak and as well as autoreleased objects :)
like:
NSMutableString *aString = [[NSMutableString alloc] initWithString:@"asdasd"];
for(int i=0; i<1000 ; i++)
[aString appendString:@"asdasd"];
[aString release];
aString = nil;
This is the main difference b/n Mutable and immutable String:
Avoids Autoreleased objects.
Avoids Memory surge.
Cleaning memory is easier and efficient.
I would be afraid NSMutableString would try to optimize and leave the string in memory. If you want more control try allocating your own memory then create an NSString with it. If you do that you can overwrite the memory before you release it.
char* block = malloc(200);
NSString* string = [[NSString alloc] initWithBytesNoCopy:length:encoding:freeWhenDone];
//use string
memset(block, 0, 200);// overwrite block with 0
[string release];
free(block);