I have a UITextField and in the delegate class I have a UITableView. Here is the code:
- (BOOL) textField: (UITextField *)theTextField shouldChangeCharactersInRange: (NSRange)range replacementString: (NSString *)string {
value = [[theTextField.text stringByReplacingCharactersInRange:range withString:string] retain];
[valueTable reloadData];
return YES;
}
“value” is an NSString declared at the top of my class as “NSString *value;” and “valueTable” is just a UITableView. When I test for memory leaks, I am getting a “100%” memory leak on the line “value = [[theTextField.text stringByReplacing…” and I tried removing the “retain” on that line. However then later on when I called upon “value,” it was nil, which is not good.
So how can I fix the memory leak? And what is the memory leak? Thanks!
The memory that is being leaked is the memory pointed to by
value.Every time your text field changes, the method
stringByReplacingCharactersInRange...is returning an autoreleased NSString object. You are correct to retain it, so that it isn’t deallocated. The problem, is that you now own memory somewhere. (You own that NSString by retaining it.)The next time that method is called, when the user changes the text in that field, you’re pointing
valueto a completely different memory location. The original memory that you had retained still exists, and will continue to persist forever. (Since you never released it.)It’s very important to match any
retainmethod calls with an associatedrelease. You could do either:OR
You can define the
NSString *valueas a property on your class, like:Then simply use:
Also, since you’re always going to have retained memory after that method has been called, you’ll need to release
valuewhen your class is deallocated, as was mentioned in another answer:Edit: It sounds like you should definitely read Apple’s memory management guide before continuing:
http://developer.apple.com/library/mac/#documentation/cocoa/conceptual/MemoryMgmt/MemoryMgmt.html