开发者

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

In my program, I tried to开发者_JS百科 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?


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.


-(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


When you copy an object, you take ownership of the copy. setObject:forKey: retains objects before they are added; this means that you have over-retained userInput and placeholder: they will never be deallocated. To fix your memory leaks, relinquish ownership of the objects by calling autorelease.

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

I recommend you read Apple's Memory Management Programming Guide.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜