<<精通iOS开发>>第14章例子代码彻底清除警告

大熊猫猪·侯佩原创或翻译作品.欢迎转载,转载请注明出处.
如果觉得写的不好请多提意见,如果觉得不错请多多支持点赞.谢谢! hopy ;)


上一篇我们解决了<<精通iOS开发>>中的一个小缺陷,但是因为该书成书较早所以例子代码中还有一些警告需要清除.

警告的主要内容是使用了已经废弃的UIAlertView对象及其回调方法,下面我们就来设法将这些警告全部清除掉.

首先将Alert按钮回调方法重构为一个新的方法:

-(void)createTinyPixFile:(NSString*)fn{
    if (!fn || fn.length == 0) return;

    NSString *filename = [NSString stringWithFormat:@"%@.tinypix",fn];
    NSURL *saveUrl = [self urlForFilename:filename];
    _chosenDoc = [[HyTinyPixDocument alloc]initWithFileURL:saveUrl];
    [_chosenDoc saveToURL:saveUrl forSaveOperation:UIDocumentSaveForCreating
        completionHandler:^(BOOL success){
            if (success) {
                [self reloadFiles];
                [self performSegueWithIdentifier:@"masterToDetail" sender:self];
            }else{
                NSLog(@"failed to save!");
            }
    }];
}

该方法的作用是由文件名创建对应的文档对象,我们很快就会用到这个方法.

接下来删除alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex方法.

然后我们删除insertNewObject中的内容,并将以下代码放入该方法中:

UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Filename"
                                message:@"Enter a name for your new TinyPix document"
                                            preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"Cancel" style:
                                    UIAlertActionStyleCancel handler:nil];
    UIAlertAction *createAction = [UIAlertAction actionWithTitle:@"Create" style:
                                UIAlertActionStyleDestructive handler:^(UIAlertAction *action){
                                    NSString *fn = alert.textFields[0].text;
                                    [self createTinyPixFile:fn];
                                }];
    [alert addTextFieldWithConfigurationHandler:^(UITextField *textField){
        textField.placeholder = @"请输入文件名";
        textField.textAlignment = NSTextAlignmentCenter;
    }];
    [alert addAction:cancelAction];
    [alert addAction:createAction];
    [self presentViewController:alert animated:YES completion:nil];

现在编译运行App,所有警告都清除了,而且我们在原有功能不变的基础上得到了一个更简单的代码逻辑:

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

大熊猫侯佩

赏点钱让我买杯可乐好吗 ;)

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值