big memory problem in objective c
i've a function like this:
@property(nonatomic,retain) NSMutableArray *array;
@synthesize array = _array;
(NSMutableArray *) name
{
self.array = [[NSMutableArray alloc]init];
[_array addObject:object];
[object release];
return [_array autorelase];
}
In the other function i've a property like the property above, named result, and i make:
self.result = [... name];
Then in dealloc i make
[_result release];
and it crashes in this point, how can i solve this? I've tried many roads, but or it crashes, or i see memory leak in Instruments, where am i 开发者_运维知识库wronging?
Thanks.
While there's a lot wrong with this code, the likely cause of your crash is that you're releasing object
within -name without taking ownership of it- unless you're creating object
within the method through a call to -alloc, -new, or -copy, that method doesn't own it and isn't responsible for releasing it. This is causing that object to be invalid within the NSMutableArray, so when _result releases, it attempts to release an invalid piece of memory and crashes.
Also, properties aren't simply local variables for individual functions, they're member variables for instances of the class for which you're writing these classes. If your end goal is only to return an autoreleased array and set it to result you could do the following:
- (NSMutableArray *) name {
//call a convenience method- it comes back autoreleased
NSMutableArray* theArray = [NSMutableArray array];
[theArray addObject:object];
//don't release object unless you took ownership of it in this function
return theArray;
}
then outside the function, either call self.result = [... name]
or [self setResult:[... name]];
You have a very strange method definition (the header should have a -
before the return type), and inside that definition you are accessing a variable called object
that doesn't seem to exist. I'm not sure what you want, but you've got at least one memory problem. The array that you create in name
gets leaked every time the method is called. If you add some details, like the crash message, someone may be able to help more.
精彩评论