简体   繁体   中英

How can I avoid keeping the contents of NSData in active memory?

My app requires data such as images and video to be sent across a network. I managed to split the files up into smaller chunks using an acceptable amount of RAM, like so:

NSData *data = UIImageJPEGRepresentation([UIImage imageNamed:@"image.jpg"], 1.0);
NSArray *array = [data splitIntoSubdataWithLength:1000000];

-(NSArray *)splitIntoSubdataWithLength:(int)subdataLength {

    NSMutableArray *array = [[NSMutableArray alloc] init];

    NSUInteger dataLength = [self length];
    NSUInteger offset = 0;
    do {
        NSUInteger thisChunkSize = dataLength - offset > subdataLength ? subdataLength : dataLength - offset;


        NSData* chunk = [NSData dataWithBytesNoCopy:(char *)[self bytes] + offset
                                             length:thisChunkSize
                                       freeWhenDone:NO];

        offset += thisChunkSize;

        [array addObject:chunk];
        NSLog(@"chunk size: %i", chunk.length);

    } while (offset < dataLength);

    return array;

}

The problem is, if the original NSData object is 26MB, the RAM goes up to ~26MB. Do I need to have the entire contents of the NSData object active in memory like this, or would i be able to reduce the memory usage in any way?

you can use a memory mapped file, and store the values temporarily on disk. here's a good implementation for ios with ARC.

http://www.cimgf.com/2012/02/17/extending-nsdata-and-not-overriding-dealloc/

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