1

Will this bit of code produce any memory leaks? Is it the correct way to change NSString values?

NSString * enemiesAndElementsTextureFileName = @"bla bla";
enemiesAndElementsTextureFileName = @"bl";
2
  • You should use NSMutableString. Commented Jun 9, 2013 at 14:26
  • 3
    It won't produce memory leak. It is valid code and is a very common usage, so you might want to clarify yourself why you doubt anything could go wrong with that. Commented Jun 9, 2013 at 14:45

3 Answers 3

3

That way of doing it won't cause any memory leaks and it is indeed correct. In this case you wouldn't need an NSMutableString because you aren't altering the string literal itself, you are simply replacing the string value with a new one (replacing @"bla bla" with @"bl").

In this case, however, your string will now be 'bl', so you can delete that first line value and just have NSString * enemiesAndElementsTextureFileName = @"bl";

Sign up to request clarification or add additional context in comments.

Comments

1

Yes NSString allocated once. This is one of the way

2 Comments

...are you saying "yes is correct" or "yes it will produce memory leaks"? I assume the first option. So the previous string will not be leaked in memory somewhere ?
Even if it was not allocated, literal @"foo" is literally equal to [[NSString alloc]initWithString:@"foo"];
1

Yes, use NSMutableString with the following method as your needs:

// Allocate  
NSMutableString *str = [[NSMutableString alloc] initWithCapacity:10];  
// set string content  
[str setString:@"1234"];  

// Append  
[str appendString:@"567"];  

// Concat  
[str appendFormat:@"age is %i and height is %.2f", 27, 1.55f];  

// Replace 
NSRange range = [str rangeOfString:@"height"];//查找字符串height的位置  
[str replaceCharactersInRange:range withString:@"no"];  

// Insert  
[str insertString:@"abc" atIndex:2];  

// Delete  
range = [str rangeOfString:@"age"];  
[str deleteCharactersInRange:range];  
NSLog(@"%@", str);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.