objective-cnsstringnsmutablestring

Remove the first characters of NSMutableString without resetting


I use NSMutableString to save a results buffer, which I want to flush when it reaches 9999 characters. I have a simple method that builds this string (appends a NSString to its end):

for(NSString* val in someStrArray)
{
    [_resultsBuffer appendString:val];
}

and I want another method that flushes this NSMutableString. This method should be able the be called from another thread, which means that the string can be built in the same time it's going to be cut.

Any way I can "silently" cut the start of the string without resetting it? (I can't reset because the string might be built and I potentially lose data if I reset the variable).


Solution

  • NSMutableString is not thread safe. And you can't modify string when it is in any operation like append string with iteration.

    You should wait until completion of such operations or stop operation first and then do modifications.

    It's same like you are watching video and same time you needs to rename video. In this case either you needs to stop video or wait for video completion.

    So if you can flush data only when your string is not in any operation.