I'm trying to get this loop to free all of the memory it uses, but it still gobbles up RAM pretty quickly. Hopefully someone can tell me how I can get the strings deallocating as they should. Basically, the loop writes doubles to a text file, and sometimes it has to write several megabytes of them.
for (int i = 0; i < number_of_samples; i++)
{
if (print_str == nil)
{
print_str = [[NSMutableString alloc] init];
}
NSString* add_str = [[NSString alloc] initWithFormat:@"\n%0.06f", number_of_seconds/number_of_samples*i];
[print_str appendString:add_str];
[add_str release];
开发者_开发知识库for (int g = 0; g < number_of_channels; g++)
{
add_str = [[NSString alloc] initWithFormat:@"\t%f", data_buffer[g + i*number_of_channels]];
[print_str appendString:add_str];
[add_str release];
}
if (i % 100 == 0 && i != 0)
{
fprintf(c_file_handle, "%s", [print_str UTF8String]);
[print_str release];
print_str = nil;
}
}
The only thing you can do with the string is not using the print_str cause it still holds all the strings and occupies memory. Use "a" option in fopen to append data to the file and append the formatted string add_str to the file instead of adding it to the memory buffer.
Because you're basically using that one string as a temporary buffer, how about allocating it once, and initWithFormatting it as often as you want? Then release it when you're done with the loop.
NSString * add_str = [NSString alloc];
loop... {
NSString* add_str = [ add_str initWithFormat:@"\n%0.06f", number_of_seconds/number_of_samples*i];
[print_str appendString:add_str];
}
// end of loop
[add_str release];
Instead of creating strings and using fprintf
, you might try using NSOutputStream
. Your code might look something like this:
NSOutputStream *os = [NSOutputStream outputStreamToFileAtPath:@"/path/to/file.ext"
append:YES];
[os open];
for (int i = 0; i < number_of_samples; i++) {
// create a buffer to store the data to write
[os write:buffer maxLength:bufferLength];
// release the buffer
}
[os close];
This is a rough sketch - see the documentation for NSStream and NSOutputStream for details.
You could use
[print_str appendFormat:]
instead of allocating and releasing a new string each time.When running in tight loops sometimes you need to create an
NSAutoRelease
pool and periodically drain it and create a new one but I do not see you using any autoreleased objects.Are you able to
free
thedata_buffer
as you go or do you use it again later?free(data_buffer[g + i*number_of_channels]);
精彩评论