mm24
mm24

Reputation: 9606

iOS: changing NSString value

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

NSString * enemiesAndElementsTextureFileName = @"bla bla";
enemiesAndElementsTextureFileName = @"bl";

Upvotes: 1

Views: 1381

Answers (3)

malajisi
malajisi

Reputation: 2243

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);

Upvotes: 1

jfuellert
jfuellert

Reputation: 570

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";

Upvotes: 3

Prateek Prem
Prateek Prem

Reputation: 1544

Yes NSString allocated once. This is one of the way

Upvotes: 1

Related Questions