views:

232

answers:

1

Hi Everyone, I have problem with this code, it's working on debug environment. On the instruments i'm seeing memory leak problem on this function, instruments is giving warning that

Category Event Type Timestamp Address Size Responsible Library Responsible Caller 27 SocialNetwork Malloc 00:19.951 0x3d64d20 80 Foundation -[NSKeyedUnarchiver _decodeArrayOfObjectsForKey:]

- (NSMutableArray *)GetDataInstanceToUserDefaults{
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults]; 
NSData *storedObject = [userDefaults objectForKey:@"MyDataKey"];
NSMutableArray *data; 

if(storedObject != nil)
{  
 NSArray *savedArray = [NSKeyedUnarchiver unarchiveObjectWithData:storedObject];
 if(savedArray != nil)
  data = [[NSMutableArray alloc] initWithArray:savedArray];
 else
  data = [[NSMutableArray alloc] init];
}else{
 data = [[NSMutableArray alloc] init]; 
} 
return data;

}

I didn't understand where is the my problem ?

Thank you for your support

Edit : By the way i should give more detail about this problem,this fucntion (as you can see) is storing my object. My object is custom class and storing in the NSMutableArray.

I already added these methods inside of the my custom class

-(void)encodeWithCoder:(NSCoder *)coder{
-(id)copyWithZone:(NSZone*)zone {
-(id)initWithCoder:(NSCoder *)coder{
+1  A: 

I think the problem is most likely in the initWithCoder: method of your custom class. It is leaking but the analyzer reports it as being in the archiver.

Unrelated to your problem, I would caution you against using [[NSMutableArray alloc] init] to initialize collections, especially mutable collections. Instead use, [[NSMutableArray alloc] initWithCapacity:1]. I've seen strange problems using just init that were cleared up by using initWithCapacity.

TechZen
TechZen thank you again your quick response. So, what should i do for solving my problem ?
fyasar
TechZen after see your answer i researched over the stackoverflow, Stefan von Chossy already gave an answer that related with my problem, if someone have same problem like me, look at here : http://stackoverflow.com/questions/537044/storing-custom-objects-in-an-nsmutablearray-in-nsuserdefaults/751749#751749 In the custom class you should use -(id)initWithCoder:(NSCoder *)coder{ self = [super init];instead of;- (id)initWithCoder:(NSCoder *)coder;{ self = [[CustomObject alloc] init]; Thank you again
fyasar