简体   繁体   中英

dispatch_async Memory Issues

I am calling the following code on touchesEnded in my drawing application. However, every time this is called, the memory usage goes up by about 2MB. Eventually it can be around 90-100MB and then the app will crash, if the user draws quickly.

What am I doing wrong here? How can I make this code speedy but with minimal memory usage?

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{

    if(_pagessavedbg.count > selectedIndex)
        self.topimage = [[UIImage alloc] initWithCGImage:[[_pagessavedbg objectAtIndex:selectedIndex] CGImage]];

    else
        self.topimage = [[UIImage alloc] initWithCGImage:[[UIImage imageNamed:@"BlankImage.png"] CGImage]];

    UIImage *bottomimage = [notification.userInfo objectForKey:@"Image"];

    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

    NSError *error2 = nil;

    NSURL *documentsURL = [[NSFileManager defaultManager]
                           URLForDirectory:NSDocumentDirectory
                           inDomain:NSUserDomainMask
                           appropriateForURL:nil
                           create:YES
                           error:nil];

    CGSize size = CGSizeMake(874, 732);
    UIGraphicsBeginImageContextWithOptions(size, NO, 1);
    [self.topimage drawInRect:CGRectMake(0, 0, size.width, size.height)];
    [bottomimage drawInRect:CGRectMake(0, 0, size.width, size.height)];
    UIImage *latest = UIGraphicsGetImageFromCurrentImageContext();
    [activeView.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *latest2 = UIGraphicsGetImageFromCurrentImageContext();
    CGContextFlush(UIGraphicsGetCurrentContext());
    UIGraphicsEndImageContext();

    if(_pages.count > selectedIndex)
    {
    if([_pages objectAtIndex:selectedIndex])
    [_pages replaceObjectAtIndex:selectedIndex withObject:latest];
    }

    if(_pages.count > selectedIndex)
    {
    if([_pagessavedbg objectAtIndex:selectedIndex])
    [_pagessavedbg replaceObjectAtIndex:selectedIndex withObject:latest2];

    else
    [_pagessavedbg insertObject:latest2 atIndex:selectedIndex];
    }

    NSData *data = UIImageJPEGRepresentation(latest, 1.0);

    NSError *error = nil;

    NSDictionary *fileObjectMap = @{
    @"ImageData" : data,
    };

    for (NSString *filename in fileObjectMap)
    {
        NSData       *data = [NSPropertyListSerialization
                              dataWithPropertyList:fileObjectMap[filename]
                              format:NSPropertyListXMLFormat_v1_0
                              options:0
                              error:&error];

        if (!data) {
            NSLog(@"Failed to serialize array for filename %@ (contents %@) with error %@", filename, fileObjectMap[filename], error);
            return;
        }

        NSURL        *fileURL = [[documentsURL URLByAppendingPathComponent:filename]
                                 URLByAppendingPathExtension:@"txt"];

        if (![data writeToURL:fileURL options:NSDataWritingAtomic error:&error]) {
            NSLog(@"Failed to write data to file URL %@ for filename %@ (data %@) with error %@", fileURL, filename, data, error);
            return;
        }
    }

    NSString *indexnotext = [defaults objectForKey:@"IndexNumber"];
    myInt = [indexnotext intValue];

    dispatch_async(dispatch_get_main_queue(), ^{
    [self.sidebar reloadData];
    [self.sidebar scrollRowAtIndexToVisible:_sidebar.selectedIndex];
    });    

    if (!documentsURL) {
        NSLog(@"Failed to get documents URL: %@", error2);
        return;
    }

    NSMutableArray *imageDatas = [NSMutableArray arrayWithCapacity:self.pages.count];

    for (UIImage *image in [_pages copy])
    {

        if(!image)
        break;

        else
        [imageDatas addObject:UIImageJPEGRepresentation(image, 1.0)];

    }

    NSMutableArray *imageDatas2 = [NSMutableArray arrayWithCapacity:self.pagessavedbg.count];

    for (UIImage *image2 in [self.pagessavedbg copy])
    {
        if(!image2)
        break;

        else
        [imageDatas2 addObject:UIImageJPEGRepresentation(image2, 1.0)];

    }

    NSDictionary *fileObjectMap2 = @{
    [NSString stringWithFormat:@"SavedPages%i", [_indexnumber intValue]] : imageDatas,
    [NSString stringWithFormat:@"SavedPagesBG%i", [_indexnumber intValue]] : imageDatas2,
    };

    for (NSString *filename2 in fileObjectMap2)
    {
        self.data2 = [NSPropertyListSerialization
                              dataWithPropertyList:fileObjectMap2[filename2]
                              format:NSPropertyListXMLFormat_v1_0
                              options:0
                              error:&error2];

        if (!self.data2) {
            NSLog(@"Failed to serialize array for filename %@ (contents %@) with error %@", filename2, fileObjectMap2[filename2], error2);
            return;
        }

        NSURL        *fileURL2 = [[documentsURL URLByAppendingPathComponent:filename2]
                                 URLByAppendingPathExtension:@"txt"];

        if (![self.data2 writeToURL:fileURL2 options:NSDataWritingAtomic error:&error2]) {
            NSLog(@"Failed to write data to file URL %@ for filename %@ (data %@) with error %@", fileURL2, filename2, self.data2, error2);
            return;
        }

    }

});

Use the Instrument Tool For XCODE

  1. Click Product -> Profile
  2. Click the Leaks
  3. Check the Link

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