Will this bit of code produce any memory leaks? Is it the correct way to change NSString values?
NSString * enemiesAndElementsTextureFileName = @"bla bla";
enemiesAndElementsTextureFileName = @"bl";
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";
Yes NSString allocated once. This is one of the way
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.