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

来源:互联网 发布:淘宝网注册电话 编辑:程序博客网 时间:2024/06/12 23:54

大熊猫猪·侯佩原创或翻译作品.欢迎转载,转载请注明出处.
如果觉得写的不好请多提意见,如果觉得不错请多多支持点赞.谢谢! 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,所有警告都清除了,而且我们在原有功能不变的基础上得到了一个更简单的代码逻辑:

这里写图片描述

1 0
原创粉丝点击