示例1:正常写法 NSData *data=[NSData dataWithContentsOfFile:[[NSBundle mainBundle]pathForResource:@"photo" ofType:@"jpg"]];
 NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
//写入100张图片到沙盒中,观察内存
    for (int i=0; i<100; i++) {
        NSString *photoPath=[path stringByAppendingPathComponent:[NSString stringWithFormat:@"photo_%zi",i]];
        UIImage *image = [[UIImage alloc] initWithData:data];
        [UIImagePNGRepresentation(image) writeToFile:photoPath atomically:YES];
 }
示例二:写完指向nil NSData *data=[NSData dataWithContentsOfFile:[[NSBundle mainBundle]pathForResource:@"photo" ofType:@"jpg"]];
 NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
 for (int i=0; i<100; i++) {
        NSString *photoPath=[path stringByAppendingPathComponent:[NSString stringWithFormat:@"photo_%zi",i]];
        UIImage *image = [[UIImage alloc] initWithData:data];
        [UIImagePNGRepresentation(image) writeToFile:photoPath atomically:YES];
         image=nil;
    }示例三:使用自动释放池释放NSData *data=[NSData dataWithContentsOfFile:[[NSBundle mainBundle]pathForResource:@"photo" ofType:@"jpg"]];
 NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
for (int i=0; i<100; i++) {
        NSString *photoPath=[path stringByAppendingPathComponent:[NSString stringWithFormat:@"photo_%zi",i]];   
        @autoreleasepool {
            UIImage *image = [[UIImage alloc] initWithData:data];
            [UIImagePNGRepresentation(image) writeToFile:photoPath atomically:YES];
        }    
    }输出结果:问题:
1.即使使用了autoreleasepool,写入过程内存最高值还是很高,手机程序可能崩溃,怎么解决?
2.指向nil,不是将该指向该对象的指针指向空,但实际该对象的内存还存在,并没释放掉?
3.运行前17.7MB,运行后最低21MB,多出来的3MB哪里来?

解决方案 »

  1.   

    楼主前两种用法,确定已经对源文件启用 -fobj-arc 编译开关了吗?
    第三种的 autoreleasepool 只包含了一小部分代码, 其他的难道不需要吗?
      

  2.   

    前两个默认是arc 没有禁止 arc下不是会自动回收 其次第三个只是两个对象data和path没放进去autorelease 但arc下不是会自动释放?
      

  3.   

    试一下:
     NSData *data=[NSData dataWithContentsOfFile:[[NSBundle mainBundle]pathForResource:@"photo" ofType:@"jpg"]];
     NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
     for (int i=0; i<100; i++) {
            NSString *photoPath=[path stringByAppendingPathComponent:[NSString stringWithFormat:@"photo_%zi",i]];
            UIImage *image = [[UIImage alloc] initWithData:data];
            NSData *data1 = UIImagePNGRepresentation(image);
            [data1 writeToFile:photoPath atomically:YES];
            data1 = nil;
             image=nil;
        }
    data = nil
      

  4.   

    没差别 结果是:18MB 49.1MB 36.2