I’m having a bit of trouble with memory leaks in my objective c code. Could anyone take a look and let me know what they think?
NSStringArray.h
@interface NSStringArray : NSObject {
NSMutableArray *realArray;
}
@property (nonatomic, assign) NSMutableArray *realArray;
-(id)init;
-(void)dealloc;
@end
NSStringArray.m
#import "NSStringArray.h"
@implementation NSStringArray
@synthesize realArray;
-(id)init {
self = [super init];
if ( self != nil ) {
realArray = [[[NSMutableArray alloc] init] retain];
}
return self;
}
-(void)dealloc {
[realArray release];
realArray = nil;
[super dealloc];
}
Factory.m
+(NSStringArray *)getFields:(NSString *)line {
//Divides the lines into input fields using "," as the separator.
//Returns the separate fields from a given line. Strips out quotes & carriage returns.
line = [line stringByReplacingOccurrencesOfString:@"\"" withString:@""];
line = [line stringByReplacingOccurrencesOfString:@"\r" withString:@""];
NSStringArray *fields = [[NSStringArray alloc] init];
for (NSString *field in [line componentsSeparatedByString:@","]) {
[fields.realArray addObject:field];
[field release];
}
return [fields autorelease];
}
The Leaks tool is saying that the leak occurs when fields is allocated, and when I am adding field string to the fields array.
Also, this function is getting called each line of a file that I’m parsing.
Any tips would be helpful.
Thanks!
In this piece of code, you break the memory management rules.
You do not own the object pointed at by
fieldso you must not release it.You have overreleased field so the last object to release it (the autorelease pool in your case) is releasing an already dealloc’d object.