简体   繁体   中英

NSString: how to use substring in a loop?

sText is an instance variable of type NSString. No properties are involved.

The loop below is supposed to get the first character of sText and store that char in sCurrentCharacter. Then the rest of sText should be reassigned to sText. This goes on until the string has been eaten up. (I left out all the code which actually does something sensible to the variables).

while ([sText length] > 0)
{
// Get the current first ASCII character.
NSString *sCurrentCharacter = [sMorseText substringToIndex:1];
// Keep everything but the first character.
sText = [sText substringFromIndex:1];
}

Questions: do I have to release sText before reassigning the result of "substringFromIndex"? If yes: why? If not: why not? :-)

René

That depends on how you created the initial sText . If sText is an autoreleased object or you have not explicitly retained it, then you are fine. If you created sText using init , copy or retain ed it, then you should autorelease it before the while loop.

so this is fine:

NSString *sText = @"foo";
while ([sText length] > 0){
   // Get the current first ASCII character.
   NSString *sCurrentCharacter = [sMorseText substringToIndex:1];
  // Keep everything but the first character.
  sText = [sText substringFromIndex:1];
}

This will leak the original value of sText :

NSString *sText = [myString retain];
while ([sText length] > 0){
   // Get the current first ASCII character.
   NSString *sCurrentCharacter = [sMorseText substringToIndex:1];
  // Keep everything but the first character.
  sText = [sText substringFromIndex:1];
}

Memory management issues aside, this is a rather inefficient approach in Objective-C (but great for LISP!). A more efficient approach would be:

NSUInteger iter, length = sText.length; // Only call -length once.
for (iter = 0; iter < length; iter++)
{
    unichar c = [sText characterAtIndex:iter];
    // Or, if you actually need it as an NSString:
    NSString *substr = [sText substringWithRange:(NSRange){ iter, 1 }];
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM