异常: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;

}

 

你可能感兴趣的:(异常:NSException和NSAssert的简单使用)