异常:NSException和NSAssert的简单使用

//断言

- (void)NSAssert_Test:(NSString *)string{
    NSAssert(string == nil, @"string == kong  or nil");
}

-----------------------------------------------------------------

//异常

- (void)NSException_Test{
    _num++;
    NSException *excep = [[NSException alloc] initWithName:@"BENG" reason:@"dian l 3 xia!" userInfo:@{@"reason": @"3 times clicked!"}];
    @try {
     switch (_num) {
            case 3:{
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:excep.name message:excep.reason delegate:nil cancelButtonTitle:nil otherButtonTitles:nil, nil];
                alert.alertViewStyle = UIAlertViewStyleLoginAndPasswordInput;
                [alert textFieldAtIndex:0].text = excep.userInfo[@"reason"];
                [alert textFieldAtIndex:1].placeholder = @"enter:123";
                [alert textFieldAtIndex:1].delegate = self;
                [alert show];
                _alert = alert;
                @throw excep;//num==3抛出异常
            }break;
            default:
                break;
        }
        NSLog(@"try:%d",_num);
    }
    @catch (NSException *exception) {//捕获异常
        _num = 0;
        NSLog(@"catch:%@--%@",exception,exception.userInfo);
    }
    @finally {
        NSLog(@"finally:");
    }
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    NSString *all = [textField.text stringByReplacingCharactersInRange:range withString:string];
    if ([all isEqualToString:@"123"]) {
        [_alert dismissWithClickedButtonIndex:0 animated:YES];
    }
    return YES;
}

 链接:

断言(NSAssert)的使用

iOS被开发者遗忘在角落的NSException-其实它很强大

原文地址:https://www.cnblogs.com/On1Key/p/5144857.html