2017-01-07 4 views
0

저는 iOS 프로젝트에서 작업하고 있습니다. 한가지 주목할 점은 오류를 표시해야 할 때마다 경고음을 반복해서 생성한다는 것입니다. 중복을 제거하는 코드를 리팩토링하고 싶습니다. 내 질문은 :이 특정 시나리오에 대한 리팩토링에 대한 적절한 접근 방식으로 클래스를 처리하는 오류를 만드는 것입니까? 예를 들어, 나는 다음과 같은 클래스alertbox를 표시하는 코드 리펙토링 (적절한 접근 방법은 무엇입니까?)

class ErrorHandler { 

    func ShowAlertBox(Title: String, Message: String, ViewController: UIViewController) { 

      let alertController = UIAlertController(title: Title, message: Message), preferredStyle: .Alert) 
      let doneAction = UIAlertAction(title: NSLocalizedString("Cancel", comment: "Label to cancel sign-in failure."), style: .Cancel, handler: nil) 
    alertController.addAction(doneAction) 
      ViewController.presentViewController(alertController, animated: true, completion: nil) 
    } 
} 

을 만들 것입니다 그리고 다음과 같이 호출

instanceofErrorHandler.ShowAlertBox("Error","Log In Error", SignInViewController) 
+1

나는 클래스와 변수 사이의 차이를 표시하는 낙타 표기법을 사용하는 것이 좋습니다 것입니다. – Emptyless

+1

관련이 없지만 표준 명명 규칙을 사용하는 방법을 배우십시오. 변수, 속성 및 메서드 이름은 모두 소문자로 시작해야합니다. 클래스 이름은 대문자로 시작합니다. 다음 표준은 코드를 읽기 쉽도록 만듭니다 (스택 오버플로에서 제대로 채색됩니다). – rmaddy

+1

@Emptyless OP가 camelcase를 사용 중입니다. 문제는 변수 이름과 메소드 이름을 대문자로 시작하는 것입니다. – rmaddy

답변

1

나는이 시나리오를 처리하는 방법에 대한 다른 의견이 많이있다 생각하고 내가 어떤 문제를 볼 수 없습니다 당신의 접근 방식. 즉 말했다, 나는 그것이 확장을 만드는 것입니다 할 방법은 ViewControllerUtilities라고하고 거기에 내 일반적인 모든 기능을 넣어 :

protocol ViewControllerUtilities {} 

extension ViewControllerUtilities where Self: UIViewController { 
    func showAlert(_ title: String = "Error", message: String) { 
     let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert) 
     alertController.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil)) 
     present(alertController, animated: true, completion: nil) 
    } 
} 

참고로, 나는 또한 네트워크가 도달 할 수 있는지 확인하기 위해 거기에 기능을 가지고 있습니다. 그럼 난 단순히 내보기 컨트롤러에 따르는 프로토콜 목록에 ViewControllerUtilities을 추가하여 모든 기능을 얻을 :

class MyViewController: UIViewController, ViewControllerUtilities { 

    override func viewDidAppear(_ animated: Bool) { 
     super.viewDidAppear(animated) 

     showAlert("Error", message: "Sorry, had an error.") 
    } 

} 
+0

나는 그것이 좋은 생각이라고 생각한다. 하지만 한 가지 질문. "어디서 Self : UIViewController"를 사용했는지 본 적이 없습니다. 귀하의 예제에서, 나는 그것이 ViewControllerUtilities가 UIViewController 클래스에서 상속 받았다고 가정합니다. 그게 맞습니까? 그리고 "_ title : String"이 오타라고 가정합니다. – user30646

+0

@ user30646 아니요,'_ title : String'은 오타가 아닙니다. – rmaddy

+0

@rmaddy : 그것은 무엇을합니까? – user30646