- (BOOL)textFieldShouldEndEditing:(UITextField *)textField
{
static NSCharacterSet *charSet = nil;
if (!charSet) {
charSet = [[[NSCharacterSet characterSetWithCharactersInString:@"0123456789."] invertedSet] retain];
}
NSRange loc = [(NSString*)textField.text rangeOfCharacterFromSet:charSet];
if (loc.location != NSNotFound) {
UIAlertView *errorAlert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"error!",@"")
message:@"description."
delegate:self
cancelButtonTitl开发者_如何学Ce:NSLocalizedString(@"OK",@"")
otherButtonTitles:nil];
[errorAlert show];
[errorAlert release];
return NO;
}
return YES;
}
I have a question connected with autorelease.
I know that when I create object in that way:
charset =[[NSCharacterSet characterSetWithCharactersInString:@"0123456789."] invertedSet];
object is autoreleased.
And I have question - reason for why there is a retain, on this object, is that - object is released after first call function?
It's because charSet is declared as static. Normal scoping rules apply, so it's only visible within this method. But, static variables don't live on the stack, and keep their values when the method returns, so they still have the same value if it's called again. That's why there's the "if (!charSet)" - this checks to see if the object has been created yet, so the existing object can be re-used if so.
Without the -retain, the NSCharacterSet object is autoreleased, and the block of memory where it lived can (and will) be used for something else. But the charSet*
pointer to that memory is not reset to nil when that happens. It still has the old value; since that value is non-nil, the if(!charSet)
is false, so a new object won't be created. But, since the old object was destroyed, there's no telling what might be at the memory to which that pointer refers - it could be random garbage, it could be some other object, it could be anything.
精彩评论