I have a question about text field. I am writing to let the user only can enter number into the text field.
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
static NSCharacterSet *charSet = nil;
if(!charSet) {
charSet = [[[NSCharacterSet characterSetWithCharactersInString:@"0123456789"] invertedSet] retain];
}
NSRange location = [string rangeOfCharacterFromSet:charSet];
return (location.location == NSNotFound);
}
Above is the code, it works fine now, the only thing is how can I release charSet since I retain it already. If I release it here, it will crash. Please text me the way. Or is it still ok if I keep it retain like that?
You should never have retained
charSetin the first place. It is autoreleased when it comes to you: it lives long enough for the rest of your code to run, and then goes out of existence all by itself.Of course if you use iOS 5 and ARC you’ll never have to worry about retain and release again…
EDIT: Oh, I see what the problem is, you’re assigning to a static. Okay then, just retain it as you are doing, and let it leak later on. Either that or use an instance variable and that way you can memory-manage it. Sorry about getting the answer wrong the first time, but better to admit that I read carelessly… 🙂
ANOTHER EDIT: But why are you assigning to a static? Do you really think this is saving you a lot of time? Isn’t this a case of “premature optimization”? Computers are really fast, much much faster than the user can type; I think your device can very happily calculate
[[NSCharacterSet characterSetWithCharactersInString:@"0123456789"] invertedSet]every time through this routine without slowing things down.