((精通iOS開發))第14章例子代碼徹底清除警告
上一篇我們解決了<<精通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,所有警告都清除了,而且我們在原有功能不變的基礎上得到了一個更簡單的代碼邏輯: