开发者

memory leak in iPad app

I've been working a product display app but it has a memory leak that causes it to crash after too many categories have been loaded up. The app works via a SplitViewController that lists the categories down the left and, once tapped, the product images show in the detailViewController on the right. Selecting category after category eventually crashes the app.

I've used the instruments -> Leaks tool to trace the problem and I get told that NSString appendString is a leak. The number of strings leaked seems to match the number of products in the category selected so I'm guessing one of my loops holds the problem but, after playing around with AutoreleasePools I haven't solved it yet.

My code: This method is called when the category is selected and parses an XML document

- (NSMutableArray*) processXML{
//NSAutoreleasePool *pool4  = [[NSAutoreleasePool alloc] init];
// Initialize the productEntries MutableArray declared in the header
products = [[NSMutableArray alloc] init];   
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSMutableString *documentsDirectory = [[NSMutableString stringWithFormat:@"%@", [paths objectAtIndex: 0]] autorelease];
// paths to save inputs to
NSString *productsFile = [documentsDirectory stringByAppendingFormat: @"/products2.xml"];
NSData *data = [NSData dataWithContentsOfFile: productsFile];

// Create a new rssParser object based on the TouchXML "CXMLDocument" class, this is the object that actually grabs and processes the RSS data
NSError *error = nil;
CXMLDocument *rssParser = [[[CXMLDocument alloc] initWithData:(NSData *)data encoding:NSUTF8StringEncoding options:0 error:&error] autorelease];  

// Create a new Array object to be used with the looping of the results from the        rssParser
NSArray *resultNodes = NULL;

//NSString *xPathStart, *xPathEnd, *category, *finalStr;
NSString *xPathStart = [[NSString stringWithFormat:@""] autorelease];
NSString *xPathEnd = [[NSString stringWithFormat:@""] autorelease];
NSString *category = [[NSString stringWithFormat:@""] autorelease];
NSString *finalStr = [[NSString stringWithFormat:@""] autorelease];
NSString *detailStr = [[NSString stringWithFormat: detailItem] autorelease];
// category to be parsed - build up xPath expression
if([detailStr isEqualToString: @"On Order Stock"]) {
    xPathStart = @"/products/product[instock='2";
    xPathEnd = @"']";
    finalStr = [NSString stringWithFormat:@"%@%@", xPathStart, xPathEnd];

} else {
    xPathStart = @"/products/product[category='";
    category = detailItem;
    xPathEnd = @"']";
    finalStr = [NSString stringWithFormat:@"%@%@%@", xPathStart, category, xPathEnd];
}
resultNodes = [rssParser nodesForXPath: finalStr error:nil];


// Loop through the resultNodes to access each items actual data
for (CXMLElement *resultElement in resultNodes) {

    Product *productItem = [[Product alloc]  init];
    [productItem setCode: [[[resultElement childAtIndex: 1] stringValue] autorelease]];
    [productItem setImage: [[[resultElement childAtIndex: 5] stringValue] autorelease]];

    // Add the product object to the global productEntries Array so that the view can access it.
    [products addObject: productItem];

    [productItem release];
}
//[pool4 release];
return products;

}

As you can see I went a little crazy with autoReealse on my strings. The other code segment that displays the images could be the problem although Leaks does mention processXML directly.

- (void) displayImages:(NSMutableArray *)anArray {

// create scrollView object
scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 100)];
scrollView.pagingEnabled = NO;
scrollView.scrollEnabled = YES;
scrollView.backgroundColor = [UIColor colorWithRed:0.9 green:0.9 blue:0.9 alpha:1];
scrollView.userInteractionEnabled = YES;

//create info area below scrollView
infoView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height - 100,  self.view.frame.size.width, 100)];
[infoView setContentSize:CGSizeMake(self.view.frame.size.width, 100)];
infoView.backgroundColor = [UIColor colorWithRed:0.1 green:0.1 blue:0.1 alpha:1];
infoView.scrollEnabled = NO;

[barcodeImgView setImage:[UIImage imag开发者_如何转开发eNamed:@"barcode2.jpg"]];
[infoView addSubview:codeLbl];
[infoView addSubview:nameLbl];
[infoView addSubview:priceLbl];
[infoView addSubview:dimensionsLbl];
[infoView addSubview:stockLbl];
[infoView addSubview:commentsLbl];
[infoView addSubview:barcodeImgView];
infoView.userInteractionEnabled = YES;

[codeLbl setText:[[NSString stringWithFormat:@""] autorelease]];
[nameLbl setText:[[NSString stringWithFormat:@""] autorelease]];
[priceLbl setText:[[NSString stringWithFormat:@""] autorelease]];
[commentsLbl setText:[[NSString stringWithFormat:@""] autorelease]];
[stockLbl setText:[[NSString stringWithFormat:@""] autorelease]];
[dimensionsLbl setText:[[NSString stringWithFormat:@""] autorelease]];

// hold x and y of each image
int x = 30;
int y = 50;
int noOfImages = [anArray count];
int maxRowWidth = (noOfImages / 3) + 1;
int xcount = 0; // position across the row, reset to zero and drop image down when equal to (noOfImages / 3) + 1

//NSAutoreleasePool *displayPool = [[NSAutoreleasePool alloc] init];

for(int i = 0; i < noOfImages; i++) {

    // declare Product object to hold items in anArray
    Product *prod = [[Product alloc] init];
    prod = [anArray objectAtIndex: i];
    // try for image in Documents folder, later checks it exists and if not uses Resource location
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSMutableString *documentsDirectory = [[NSString stringWithFormat:@"%@", [paths objectAtIndex: 0]] autorelease];;

    // paths to save inputs to
    NSString *imgName = [[NSString stringWithFormat:@"%@/%@", documentsDirectory, [prod image]] autorelease];
    NSString *productName = [[NSString stringWithFormat:@"%@", [prod code]] autorelease];
    // create and size image
    UIImage *image = [UIImage imageWithContentsOfFile: imgName];

    // set up button
    UIButton *button= [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [button addTarget:self action:@selector(imageButtonClick:) forControlEvents:(UIControlEvents)UIControlEventTouchDown];
    [button setTitle:productName forState:UIControlStateNormal];
    button.titleLabel.font = [UIFont systemFontOfSize: 0];
    [button setTitleColor: [UIColor colorWithRed:0.1 green:0.1 blue:0.1 alpha:1] forState: UIControlStateNormal];

    CGSize imageSize = image.size;
    CGFloat height = imageSize.height;
    CGFloat width = imageSize.width;
    CGFloat ratio = 160 / width; // get ratio to divide height by
    UIGraphicsBeginImageContext(CGSizeMake((height * ratio),160));  
    CGContextRef context = UIGraphicsGetCurrentContext();
    [image drawInRect: CGRectMake(0, 0, height * ratio, 160)];  
    UIImage *smallImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    // create frame for image
    CGRect newFrame = CGRectMake(x, y, 160,160);
    UILabel *codeLabel = [[UILabel alloc] initWithFrame:CGRectMake(x, y - 20, 170, 20)];
    codeLabel.text = productName;
    codeLabel.textColor = [UIColor colorWithRed:0.1 green:0.1 blue:0.1 alpha:1];
    codeLabel.backgroundColor = [UIColor colorWithRed:0.9 green:0.9 blue:0.9 alpha:1];
    [button setFrame: newFrame];
    [button setBackgroundImage:smallImage forState:UIControlStateNormal];
    [scrollView setContentSize:CGSizeMake((maxRowWidth * 160) + 160,self.view.frame.size.height - 100)];
    [self.scrollView addSubview:button];
    [self.scrollView addSubview:codeLabel];


    xcount++;
    x = x + 170; // move across the page
    if(xcount == maxRowWidth) {
        y = y + 210;  // move down the screen for the next row
        x = 30;   // reset x to left of screen
        xcount = 0;   // reset xcount;
    }

    [prod release];
}
//[displayPool release];
[self.view addSubview: scrollView];
[self.view addSubview: infoView];
[scrollView release];
[infoView release];

[pool release];

}

By the way, pool is an autoreleasePool defined in the h file for the class.

I would really appreciate any specific help regarding my code or general tips on what could be wrong.


I see a few things wrong:

  1. As was mentioned in the comments, you're abusing -autorelease in ways which make grown men cry and that which will crash your app.
  2. -processXML is returning an owned object. You're allocating products and returning it. This breaks convention, because the method name does not begin with new or alloc, and does not contain copy. You should return [products autorelease]; instead. However, even that is shady, because since products isn't declared locally, it's probably an instance variable. In that case, what happens if processXML gets invoked multiple times? You have an owned object referenced by the instance variable, and suddenly you overwrite that reference with a new one... = memory leak.
  3. Every time someone does MyClass * object = [[MyClass alloc] init]; object = [something thatReturnsAMyClass];, a kitten dies. If you then do [object release];, a second dies for good measure. This is a terrible, terrible memory leak (and a likely crash). You're allocating a new object and then immediately throwing it away but never releasing it. That you do this suggests you don't really get what a pointer is. I suggest reading "Everything you need to know about pointers in C"
  4. On a lighter note, you should check out -[NSString stringByAppendingPathComponent:]. NSString has a bunch of really nice methods for dealing with paths.

I hope I don't come off as too harsh. :)


Some while ago at another post somebody said that one should read about the memory management and I was actually thinking that this answer is not really right. What is wrong with some trial and error and learning by doing. But after I had my painful experiences with memory I must admit that this guy was right. Take the time. Go and read the chapter on memory management in the apple documentation.

As above stated already you should not autorelease an object you do not own. But this might not cause the trouble. You can next to the instruments use Build+Analyze in the Build menu. This will help you to find out more.

Basically you need to release objects you create which you own (which one you own is in the documentation, basically those created with "alloc" and some more). If you cannot release them you assign them to the autorelease pool. This is the case with the "products" you return from processXML. When is the autorelease pool drained? This is when the next time the framework of the application is back in control (I think it was called run-loop or something). This can be a while and so you should not open to much objects which are assigned to an autorelease pool.

So to help you really read that chapter: memory management programming guide

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜