最白目
最白目

Reputation: 3634

Potential Memory Leak or Incorrect Decrement of the reference count

I have this method which

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        UIWebView *t_webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 44, 
                                                                       320,480)];
        self.webView = t_webView;
        self.accel = [[Accelerometer alloc]init];

        //Potential Memory Leak here
        NSURL *theurl = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"second" ofType:@"html" inDirectory:@"www"]];
        [self.webView loadRequest:[NSURLRequest requestWithURL:theurl]];
        [self.view addSubview:webView];

        [theurl release];//When I add this line, the Memory Leak Warning disappears, but instead I get a "incorrect Decrement of reference count
        theurl = nil;

        [t_webView release];
    }

    return self;
 }

I think I haven´t understood something about memory management, can somebody help me how to avoid the warning?

Upvotes: 0

Views: 132

Answers (1)

bbum
bbum

Reputation: 162712

NSURL *theurl = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"second" ofType:@"html" inDirectory:@"www"]];

That returns an autoreleased object. releaseing it later in the method is incorrect.

The leak is self.accel = [[Accelerometer alloc]init];; +alloc implies a retain and the assignment to a retaining property is the other. I would suggest:

Accelerometer *acc = [[Accelerometer alloc]init];
self.accel = acc;
... do stuff with `acc` ...
[acc release];

If the compiler warning comes and goes w/[theurl release], that sounds like an analyzer bug.

Upvotes: 2

Related Questions