Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to release an object which use copy keyword in iOS program

In my program, I tried to set object in an dictionary. Values are coming from another class, so I copied those values before processing it.

While analyzing the code I got leaks.

-(void)giveInput:(NSString *)userInput ForPlaceholder:(NSString *)placeholder{

    [inputValue setObject:[userInput copy] forKey:[placeholder copy]];

}

How to release the userINput and Placehoder object retain count?

like image 549
Ram Avatar asked Dec 09 '25 10:12

Ram


2 Answers

According to the Memory Management Programming Guide, you should release or at least autorelease any references you got from alloc, new or copy.

In your case, try changing [userInput copy] to [[userInput copy] autorelease]; likewise for placeholder.

EDIT: Note though, the default NSDictionary and NSMutableDictionary classes already copy keys and retain values -- see the Memory Management Programming Guide as well as the NSMutableDictionary class reference for further details. Hence, there's no need for [placeholder copy], and if you did not mean to create a separate copy of userInput, there is no need to copy it also.

like image 56
spacehunt Avatar answered Dec 11 '25 23:12

spacehunt


-(void)giveInput:(NSString *)userInput ForPlaceholder:(NSString *)placeholder{
    NSString *cpUserInput = [userInput copy];
    NSString *cpPlaceholder = [placeholder copy];
    [inputValue setObject:cpUserInput forKey:cpPlaceholder];
    [cpUserInput release];
    [cpPlaceholder release];
}

Or in a fewer lines with autorelease:

[inputValue setObject:[[userInput copy] autorelease] forKey:[[placeholder copy] autorelease]];

*when adding objects to dictionaries/arrays they get retained

like image 41
alex-i Avatar answered Dec 11 '25 23:12

alex-i



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!