开发者

Memory leak for object in array

I've started cleaning up my app before publication - using "Instruments" Leak analyzer.

I found a leak I can't plug. So I built a simple project to illustrate the problem. Please see code below. I put a button on the view to test fire the procedure "test". It always generates a leak.

First the header and code for an object named "theObj"

#import <Foundation/Foundation.h>
开发者_C百科

@interface theObj : NSObject {

NSString* theWord; } @property (nonatomic,retain) NSString* theWord;

@end

#import "theObj.h"


@implementation theObj
@synthesize theWord;

-(id) initWithObjects: (NSString *) aWord;
{
 if (self = [super init]){
  self.theWord = aWord;
 }
 return self;
}

-(void) dealloc{
[theWord release];
[super dealloc];
}

@end

Now the view controller

#import <UIKit/UIKit.h>
#import "theObj.h"

@interface LeakAnObjectViewController : UIViewController {
 NSMutableArray* arrObjects;
}
  - (IBAction)test;
@end

#import "LeakAnObjectViewController.h"

@implementation LeakAnObjectViewController

- (IBAction)test {  
 if (arrObjects == nil)
  arrObjects = [[NSMutableArray alloc] init];

 NSString* aStr = @"first";
 [arrObjects addObject:[[theObj alloc] initWithObjects:aStr]];
 [arrObjects removeAllObjects];
}  


You alloc the object, which means you own it. Then you give it to the array, which means the array owns it as well. Then the array removes it, so you are the only owner. But you don't have a reference to the object anymore, so you can't release it, so it's just leaked.


Someone really needs to learn the rules around memory management. Specifically as it pertains to ownership, etc.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜