I dont want to return manch because if i autorelease before i return it ,it becomes invalid to others. so i was thinking of this :
classA
-(NSMutableArray*)set:(NSMutableArray*)data
{
manch= [[data mutableCopy]autorelease] ;
int count=2*[data count]; //to not enter infinity loop
for(int k=0;k< count;k=k+2)
{
if(k==count-1)
[manch addObject:[NSNumber numberWithInt:![[manch objectAtIndex:k] integerValue] ] ];
}
data=[manch mutuableCopy];
return data;
}
My goal is to create a class that gets an NSMutuableArray do some calculations, than return it, and NOT TO BE DEPEND on this class anymore .
EDIT :
As people here ask.
in another classB(the user of the method above), i have in the interface :
NSMutuableArray *data ;
and on the .m file init method i have
data=[[NSMutuableArray alloc]init];
to use the function from my question, i do :
mIns=[[classA alloc]init];
data= [mIns set:[self decimalToBinary:autoWord]];
than i loose data later.
This is an incorrect statement, you can return an autoreleased object, that’s a sane thing to do. It’s worth noting that you should design your method names correctly to inform the user what sort of object is returned. Any method whose name begins with
alloc,new,copy, ormutableCopywill return a retained object. (Source)In your case, your method name is
set:, which informs the user of this method that it will return a non retained object (almost always anautoreleasedobject). This is because it isn’t prefixed with any of those words mentioned above.In that case, the issue you have is with the user of the method; they are not retaining a reference to the object being returned. As such, the user of the method should use it as so:
You can avoid these issues by using Automatic Reference Counting (ARC, More Information), which will handle this sort of memory management for you. It is still important that you use the correct naming conventions, as ARC will judge how to manage your memory based on this (in certain situations)
Update: After seeing your update, I can see the problem.
This is creating a new instance of
NSMutableArray, one which is correctly retained (due to what I mentioned before).This is replacing the object held in
datawith a new NSMutableArray, one that is autoreleased. The previous instance you created has been lost, and you’ve replaced it with another one. This new instance has not been retained, and as such, will be released unexpectedly.To fix, you need to use this instead:
You don’t need to alloc/init a variable if it will be populated by some other object later on. I strongly suggest brushing up on how this all works, this might be a good start.