可以将对象从IF语句范围中传出吗?

Jos*_*nto 0 if-statement objective-c

这是我的代码.编译器抱怨范围内未使用的变量,并使用未声明的变量超出范围.我明白那个.该对象需要在IF语句之前声明,因此可以从双方访问它.但这是扭曲.

我不能预先声明对象,因为对象将来自哪个类取决于IF语句的结果.这是我坚持使用的代码摘录.

if (!([self.defaults valueForKey:@"unofficialAPIOn"])) {

        MALInterfaceController *interface = [[MALInterfaceController alloc]init];

    }
    else{

        MALControllerUnofficial *interface = [[MALControllerUnofficial alloc]init];

    }

    [interface verifyAuth:self.usernameField.text forPassword:self.passwordField.text];
Run Code Online (Sandbox Code Playgroud)

MALInterfaceController和MALControllerUnofficial基本上都是具有相同方法等的类,但是针对两个不同的API进行了定制.如何向上传递*interface对象?

Ste*_*oom 5

为什么不使用动态类型ID?

id interface;
if (!([self.defaults valueForKey:@"unofficialAPIOn"])) {

        interface = [[MALInterfaceController alloc]init];

    }
    else{

        interface = [[MALControllerUnofficial alloc]init];

    }

    (id<protocolWhichBothClassesConformTo>)[interface verifyAuth:self.usernameField.text forPassword:self.passwordField.text];
Run Code Online (Sandbox Code Playgroud)

此外,如果你的两个班级有"相同的方法等",这不意味着你应该看一个重构器吗?

值得一读https://developer.apple.com/library/ios/documentation/cocoa/conceptual/ProgrammingWithObjectiveC/WorkingwithProtocols/WorkingwithProtocols.html