即使我正在发布,Iphone App因收到内存警告而崩溃

时间:2012-10-31 11:24:06

标签: iphone ios memory-management ios4 didreceivememorywarning

每次进入视图使用中的内存都在增加..即使我正在保存图像。并且由于内存不足警告,应用程序崩溃了。有人可以给我解决方案,以便不增加图像内存。

     #import <UIKit/UIKit.h>
        #import "PatientStudiesViewController.h"
        #import "CareServices.h"

        @interface newImageComparison : UIViewController<UIScrollViewDelegate,ServerConnectionDelegate>
        {

            NSString *serverUrlStr;
            NSString *studyID;
            NSString *instID;
            NSString *urlEncodedKey;

            NSMutableArray *myCompareImage1;
            NSMutableArray *myCompareImage2;

            UIScrollView * _scrollView1;
            UIScrollView * _scrollView2;
            NSMutableArray *selectedStudyIDArr;
            NSMutableDictionary *SelectedImageTypeDict;
            NSMutableArray *selectedImagetypeTagsArr;
            BOOL isRightEyeSelectedAgain;
            BOOL isLeftEyeSelectedAgain;
            NSMutableArray *demoCompareODArr;
            NSMutableArray *demoCompareOSArr;
            CareServices *careServices;

        }

        -(void)prepareODImages_selectedStudyIDString1 :(NSString *)selectedIDString1;
        -(void)prepareOSImages_selectedStudyIDString2 :(NSString *)selectedIDString2;
        - (void)loadImageRightEyeImage:(NSMutableArray *)urlAndTagReference;
        - (void)loadImageLeftEyeImage:(NSMutableArray *)urlAndTagReference;


        @end


        #import "newImageComparison.h"
        #import "XMLParserForStudyDetails.h"
        #import "ColorSchemes.h"
        #import <CommonCrypto/CommonDigest.h>
        #import "mach/mach.h"



        @implementation newImageComparison

        - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
        {
            self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
            if (self) {
                // Custom initialization
            }
            return self;
        }

        - (void)didReceiveMemoryWarning
        {
            // Releases the view if it doesn't have a superview.
            [super didReceiveMemoryWarning];

            // Release any cached data, images, etc that aren't in use.
        }

        #pragma mark - View lifecycle

        - (void)viewDidLoad
        {
            careServices = [CareServices currentInstance];
            careServices.delegate = self;
            NSUserDefaults *selectedStudy = [NSUserDefaults standardUserDefaults];
            selectedStudyIDArr = [selectedStudy valueForKey:@"selectedStudyIDArray"];
            NSUserDefaults *selectedImagetype = [NSUserDefaults standardUserDefaults];
            SelectedImageTypeDict = [selectedImagetype valueForKey:@"imageTypeDict"];
            NSUserDefaults *selectedImageTypeTags = [NSUserDefaults standardUserDefaults];
            selectedImagetypeTagsArr = [selectedImageTypeTags valueForKey:@"selectedImageTypeTags"];
            NSMutableArray *imageType = [[NSMutableArray alloc]init];
            for (int count = 0; count <[selectedImagetypeTagsArr count]; count++) {

                [imageType addObject:[SelectedImageTypeDict valueForKey:[selectedImagetypeTagsArr objectAtIndex:count]]];
            }
             self.view.backgroundColor = [UIColor blackColor];
            [super viewDidLoad];
            myCompareImage1 = [[NSMutableArray alloc]init];
            myCompareImage2 = [[NSMutableArray alloc]init];
            NSUserDefaults *realUrl = [NSUserDefaults standardUserDefaults];
            serverUrlStr = [realUrl valueForKey:@"serverUrl"];
            NSString *key;
            NSUserDefaults *keyD = [NSUserDefaults standardUserDefaults];
            key = [keyD valueForKey:@"key"];
            urlEncodedKey = (NSString *) CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)key, NULL, CFSTR(":/?#[]@!$&’()*+,;="), kCFStringEncodingASCII);
            NSUserDefaults *studyID_D = [NSUserDefaults standardUserDefaults];
            studyID = [studyID_D valueForKey:@"studyID"];
            NSUserDefaults *instID_D = [NSUserDefaults standardUserDefaults];
            instID = [instID_D valueForKey:@"instID"];
            NSMutableArray *selectedDateArray = [[NSUserDefaults standardUserDefaults]valueForKey:@"selectedDateArray"];
            demoCompareODArr = [[NSMutableArray alloc]init];
            demoCompareOSArr = [[NSMutableArray alloc]init];
            UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(60, 2, 200, 20)];
            label.backgroundColor = [UIColor clearColor];
            label.text = [NSString stringWithFormat:@"%@/%@/%@",[selectedStudyIDArr objectAtIndex:0],[selectedDateArray objectAtIndex:0],[imageType objectAtIndex:0]];
            label.font = [UIFont systemFontOfSize:15];
            label.textAlignment = UITextAlignmentCenter;
            label.textColor = [UIColor greenColor];
            [self.view addSubview:label];
            [label release];


            label = [[UILabel alloc]initWithFrame:CGRectMake(60, 208, 200, 20)];
            label.text = [NSString stringWithFormat:@"%@/%@/%@",[selectedStudyIDArr objectAtIndex:1],[selectedDateArray objectAtIndex:1],[imageType objectAtIndex:1]];
            label.font = [UIFont systemFontOfSize:15];
            label.backgroundColor = [UIColor clearColor];
            label.textColor = [UIColor greenColor];
            label.textAlignment = UITextAlignmentCenter;
            [self.view addSubview:label];
            [label release];

           NSMutableDictionary *selectedDemoImagesDict = [[NSUserDefaults standardUserDefaults]valueForKey:@"selectedDemoImagesDict"];

            if ([[imageType objectAtIndex:0] isEqualToString:@"OD"]) {
                  [self prepareODImages_selectedStudyIDString1:[selectedStudyIDArr objectAtIndex:0]];
               }
               else {
                isLeftEyeSelectedAgain = YES;
                       [self prepareOSImages_selectedStudyIDString2:[selectedStudyIDArr objectAtIndex:0]];
             }

            if ([[imageType objectAtIndex:1]isEqualToString:@"OS"]) {
                       [self prepareOSImages_selectedStudyIDString2:[selectedStudyIDArr objectAtIndex:1]];

            }
            else {
                isRightEyeSelectedAgain = YES;
              [self prepareODImages_selectedStudyIDString1:[selectedStudyIDArr objectAtIndex:1]];
            }

            self.navigationItem.title = @"Image Comparsion";


            // Do any additional setup after loading the view from its nib.
        }



        - (void)viewDidAppear:(BOOL)animated {
             UIImageView *imageView1 = [[UIImageView alloc]initWithFrame:CGRectMake(27,23,265,184)];
            imageView1.image = [UIImage imageNamed:@"plainbg_3.png"];
            [self.view addSubview:imageView1];
            UIImageView *imageView2 = [[UIImageView alloc]initWithFrame:CGRectMake(27,228,265,184)];
            imageView2.image = [UIImage imageNamed:@"plainbg_3.png"];
            [self.view addSubview:imageView2];

             _scrollView1 = [[UIScrollView alloc]initWithFrame:CGRectMake(33,30,252,172)];
            _scrollView1.delegate = self;
            _scrollView1.backgroundColor = [UIColor clearColor];
            _scrollView1.pagingEnabled = YES;
            _scrollView1.scrollEnabled = YES;
            [self.view addSubview:_scrollView1];
             _scrollView2 = [[UIScrollView alloc]initWithFrame:CGRectMake(33,234,252,172)];
            _scrollView2.delegate = self;
            _scrollView2.backgroundColor = [UIColor clearColor];
            _scrollView2.pagingEnabled = YES;
            _scrollView2.scrollEnabled = YES;
            [self.view addSubview:_scrollView2];
            int x_val = -252;
            int y_val = 0;

            float dis  = 0;
            for (int seriesCount = 0; seriesCount <[myCompareImage1 count]; seriesCount++) {
                NSMutableArray *OD = [[NSMutableArray alloc]init];
                OD = [myCompareImage1 objectAtIndex:seriesCount];
                for (int count = 0; count <[OD count]; count++) {
                    dis = dis+252;
                    UIImageView *R_EyeImageView = [[UIImageView alloc]initWithFrame:CGRectMake(x_val+dis, y_val, 252, 172)];
                    R_EyeImageView.backgroundColor = [UIColor blackColor];
                    R_EyeImageView.tag = seriesCount *100+100+count;
                    [_scrollView1 addSubview:R_EyeImageView];
                    UIActivityIndicatorView *activity = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
                    [activity setFrame:CGRectMake(R_EyeImageView.frame.size.width/2.3,R_EyeImageView.frame.size.height/2.2, 40, 40)];
                    activity.tag = seriesCount*100+100+count;
                    [R_EyeImageView addSubview:activity];
                    [activity startAnimating];
                    [activity release];
                    [R_EyeImageView release];

                }
                       [self loadImageRightEyeImage:OD];
                       [OD release];
            }
            _scrollView1.contentSize = CGSizeMake(dis, 0);

            dis = 0;
            for (int seriesCount = 0; seriesCount <[myCompareImage2 count]; seriesCount++) {
                NSMutableArray *OS = [[NSMutableArray alloc]init];
                OS = [myCompareImage2 objectAtIndex:seriesCount];
                for (int count = 0; count <[OS count]; count++) {
                    dis = dis+252;
                    UIImageView *L_EyeImageView = [[UIImageView alloc]initWithFrame:CGRectMake(x_val+dis, y_val, 252, 172)];
                    L_EyeImageView.backgroundColor = [UIColor blackColor];
                    L_EyeImageView.tag = seriesCount *100+100+count;
                    [_scrollView2 addSubview:L_EyeImageView];
                    UIActivityIndicatorView *activity = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
                    [activity setFrame:CGRectMake(L_EyeImageView.frame.size.width/2.3,L_EyeImageView.frame.size.height/2.2, 40, 40)];
                    activity.tag = seriesCount*100+100+count;
                    [L_EyeImageView addSubview:activity];
                    [activity startAnimating];


                    [activity release];
                    [L_EyeImageView release];


                }

                [self loadImageLeftEyeImage:OS];

                [OS release];
            }
            _scrollView2.contentSize = CGSizeMake(dis, 0);

            [_scrollView1 release];
            [_scrollView2 release];
            [imageView1 release];
            [imageView2 release];
        }

        - (void)prepareODImages_selectedStudyIDString1:(NSString *)selectedIDString1 {
                NSMutableArray *arr = [[XMLParserForStudyDetails sharedManager].final_ImagesDict valueForKey:selectedIDString1];
                NSMutableArray *imageIDArr = [[XMLParserForStudyDetails sharedManager].imageID_RefDict_3D valueForKey:selectedIDString1];
                NSMutableArray *seriesID = [[XMLParserForStudyDetails sharedManager].SeriesRefID_Dict valueForKey:selectedIDString1];
                for (int count = 0; count <[seriesID count]; count++) {
                    NSMutableDictionary *imageDict = [arr objectAtIndex:0];
                    NSMutableArray *imageIDArr2 = [imageIDArr objectAtIndex:count];
                    NSString *seriesID1 = [seriesID objectAtIndex:count];
                    NSMutableArray *arr = [[NSMutableArray alloc]init];
                    NSMutableDictionary *imageDict2 = [imageDict valueForKey:seriesID1];
                    for (int count2 = 0; count2 <[imageIDArr2 count]; count2++) {
                        NSString *str;
                        NSMutableDictionary *imageDict3 = [imageDict2 valueForKey:[imageIDArr2 objectAtIndex:count2]];
                        if ([[imageDict3 valueForKey:@"imageType"] isEqualToString:@"image"]) {
                            if ([[imageDict3 valueForKey:@"num_frames"]isEqualToString:@"1"]) {

                                if ([[imageDict3 valueForKey:@"laterality"] isEqualToString:@"R"]) {
                                    str = [[NSString alloc]initWithFormat:@"http://%@/i2icareclientws/i2iCareAPI_Service.asmx/GetImage?key=%@&study_id=%@&series_id=%@&image_id=%@&image_level=3&format=&frame_number=&imageType=1",serverUrlStr,urlEncodedKey,selectedIDString1,seriesID1,[imageIDArr2 objectAtIndex:count2]];
                                    [arr addObject:str];
                                    [str release];

                                }
                            }
                        }
                    }
                    if (isRightEyeSelectedAgain == YES) {
                        [myCompareImage2 addObject:arr];
                        isRightEyeSelectedAgain = NO;

                    }
                    else {
                        [myCompareImage1 addObject:arr];
                    }
                    [arr release];
                }
        }


        - (void)prepareOSImages_selectedStudyIDString2:(NSString *)selectedIDString2 {
            NSMutableArray *arr = [[XMLParserForStudyDetails sharedManager].final_ImagesDict valueForKey:selectedIDString2];
            NSMutableArray *imageIDArr = [[XMLParserForStudyDetails sharedManager].imageID_RefDict_3D valueForKey:selectedIDString2];
            NSMutableArray *seriesID = [[XMLParserForStudyDetails sharedManager].SeriesRefID_Dict valueForKey:selectedIDString2];
            for (int count = 0; count <[seriesID count]; count++) {
                NSMutableDictionary *imageDict = [arr objectAtIndex:0];
                NSMutableArray *imageIDArr2 = [imageIDArr objectAtIndex:count];
                NSString *seriesID1 = [seriesID objectAtIndex:count];
                NSMutableArray *arr = [[NSMutableArray alloc]init];
                NSMutableDictionary *imageDict2 = [imageDict valueForKey:seriesID1];
                for (int count2 = 0; count2 <[imageIDArr2 count]; count2++) {
                    NSString *str;

                    NSMutableDictionary *imageDict3 = [imageDict2 valueForKey:[imageIDArr2 objectAtIndex:count2]];

                    if ([[imageDict3 valueForKey:@"imageType"] isEqualToString:@"image"]) {
                        if ([[imageDict3 valueForKey:@"num_frames"]isEqualToString:@"1"]) {

                            if ([[imageDict3 valueForKey:@"laterality"] isEqualToString:@"L"]) {

                                str = [[NSString alloc]initWithFormat:@"http://%@/i2icareclientws/i2iCareAPI_Service.asmx/GetImage?key=%@&study_id=%@&series_id=%@&image_id=%@&image_level=3&format=&frame_number=&imageType=1",serverUrlStr,urlEncodedKey,selectedIDString2,seriesID1,[imageIDArr2 objectAtIndex:count2]];
                                [arr addObject:str];
                                [str release];

                            }
                        }
                    }
                }

                            if (isLeftEyeSelectedAgain == YES) {
                                [myCompareImage1 addObject:arr];
                                isLeftEyeSelectedAgain = NO;
                            }
                            else {
                                [myCompareImage2 addObject:arr];
                             }



                [arr release];
            }

        }


        - (void)loadImageRightEyeImage:(NSMutableArray *)urlAndTagReference {
                for (int count = 0; count  <[myCompareImage1 count]; count ++) {
                for (int i = 0; i < [urlAndTagReference count]; i++) {

                    NSString *imagePath = [urlAndTagReference objectAtIndex:i];
                    imagePath = [imagePath stringByReplacingOccurrencesOfString:@"amp;" withString:@""];
                    imagePath = [imagePath stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
                    NSString* documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
                    NSString *key = [self sha1:imagePath];
                    NSString *fileToSave = [documentsPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.jpg",key]];


                    for ( UIImageView *imgView in _scrollView1.subviews) {
                        if (imgView.tag == count *100+100+i) {
                            for (UIActivityIndicatorView *activity in [imgView subviews]) {
                                if ([activity isKindOfClass:[UIActivityIndicatorView class]]) {
                                    if (activity.tag == count *100+100+i) {
                                        BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:fileToSave];
                                        if (!fileExists)
                                        {
                                            dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW,  0ul);

                                            dispatch_async(queue, ^{
                                                NSData *imageData=[NSData dataWithContentsOfURL:[NSURL URLWithString:imagePath]];


                                                UIImage *image = [[UIImage alloc] initWithData:imageData];

                                                NSData *jpegData = UIImageJPEGRepresentation(image,0.001);

                                                [[NSFileManager defaultManager] createFileAtPath:fileToSave contents:jpegData attributes:nil];

                                                dispatch_sync(dispatch_get_main_queue(), ^{
                                                    imgView.image = image;
                                                    [activity stopAnimating]; 
                                                    [activity removeFromSuperview];
                                                });
                                            });

                                        }else{
                                            UIImage *image = [UIImage imageWithContentsOfFile:fileToSave];
                                            if(!image) image = [UIImage imageNamed:@"rest-blank-thumbnail.png"];
                                            imgView.image = image;
                                            [activity removeFromSuperview];

                                        }

                                    }


                                }
                            }
                        }
                    }
                }
            }
        }


        - (void)loadImageLeftEyeImage:(NSMutableArray *)urlAndTagReference {
            for (int count = 0; count  <[myCompareImage2 count]; count ++) {

                for (int i = 0; i < [urlAndTagReference count]; i++) {

                    NSString *imagePath = [urlAndTagReference objectAtIndex:i];
                    imagePath = [imagePath stringByReplacingOccurrencesOfString:@"amp;" withString:@""];
                    imagePath = [imagePath stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
                    NSString* documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
                    NSString *key = [self sha1:imagePath];
                    NSString *fileToSave = [documentsPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.jpg",key]];


                    for ( UIImageView *imgView in _scrollView2.subviews) {
                        if (imgView.tag == count *100+100+i) {
                            for (UIActivityIndicatorView *activity in [imgView subviews]) {
                                if ([activity isKindOfClass:[UIActivityIndicatorView class]]) {
                                    if (activity.tag == count *100+100+i) {
                                        BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:fileToSave];
                                        if (!fileExists)
                                        {
                                            dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW,  0ul);
                                            dispatch_async(queue, ^{
                                                NSData *imageData=[NSData dataWithContentsOfURL:[NSURL URLWithString:imagePath]];


                                                UIImage *image = [[UIImage alloc] initWithData:imageData];

                                                NSData *jpegData = UIImageJPEGRepresentation(image,0.001);

                                                [[NSFileManager defaultManager] createFileAtPath:fileToSave contents:jpegData attributes:nil];
                                                dispatch_sync(dispatch_get_main_queue(), ^{
                                                    imgView.image = image;
                                                    [activity stopAnimating]; 
                                                    [activity removeFromSuperview];
                                                });
                                            });

                                        }else{
                                            UIImage *image = [UIImage imageWithContentsOfFile:fileToSave];
                                            if(!image) image = [UIImage imageNamed:@"rest-blank-thumbnail.png"];

                                            imgView.image = image;
                                            [activity removeFromSuperview];

                                        }

                                    }


                                    }
                                }
                            }
                        }
                       }
                   }
        }



        -(NSString*) sha1: (NSString *)str
        {
            const char *cstr = [str cStringUsingEncoding:NSUTF8StringEncoding];
            NSData *data = [NSData dataWithBytes:cstr length:str.length];

            uint8_t digest[CC_SHA1_DIGEST_LENGTH];

            CC_SHA1(data.bytes, data.length, digest);

            NSMutableString *output = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2];

            for(int i = 0; i < CC_SHA1_DIGEST_LENGTH; i++)
                [output appendFormat:@"%02x", digest[i]];
            return output;
        }



        - (void)viewDidUnload {

            _scrollView1 = nil;
            _scrollView2 = nil;

        }
        - (void)dealloc {
           [myCompareImage1 release];
            [myCompareImage2 release];

        }

2 个答案:

答案 0 :(得分:1)

如果你打开了Zombies(方案诊断),那么实际上什么也没有被删除。因此,在内存较少的设备上(如iPad 1),您将很快耗尽内存并获得内存警告。模拟器通常没有这个问题。

答案 1 :(得分:0)

您可以在XCode - Product |中使用Profiler查找内存泄漏主菜单中的配置文件。 然后选择内存 - &gt;泄漏。

另外,您可以使用Product |找到一些有趣的建议在XCode中分析。