2016-06-22 17 views

回答

2

而不是使用旧的Objective-C API,您可以在swift中使用asis关键字。

if let controller = yourViewController as? SomeClass { 
    // use controller, is already casted to SomeClass 
} 

if yourViewController is SomeClass { 
    let controller = yourViewController as! SomeClass 
    // use controller now 
} 

ADDING: 如果存储器地址不同,物体是不相等的。尝试检查答案中提到的topViewController类型。

if let topViewController = appDelegateObj.navigationController.topViewController as? YOUR_VIEW_CONTROLLER_CLASS { 
    // do something 
} 
+0

我想这样做 if appDelegateObj.navigationController!.topViewController! == myViewController {// 没有得到真实的,即使都是相同的,但内存引用不同 }其他{ //需要办理别的事情 } –

+0

感谢卢卡斯·我想它 –

1
func someMethod (someClass : AnyClass) { 
    if someClass is YourClass { 
    someClass.someMethodOfYourClass() 
    } 
} 

要使用此方法

class YouClass: UIViewController { 

    func something() { 
    someMethod(self) // sending itself (a.k.a) YourClass 

    } 
} 

希望这有助于基于评论

编辑:

let controller = appDelegateObj.navigationController!.topViewController 

if controller is ClassName { 
    // controller good to use 
} 
+0

好,谢谢 Akansha 让我检查 –

+2

好的@GopalDevra我的名字是Akshansh哈哈。 –

+0

抱歉,男人:) 谢谢Akshansh –

0

最后,我在这个解决方案达到

let name = NSStringFromClass((vcAnyObj?.classForCoder)!) 
let name2 = NSStringFromClass((appDelegateObj.navigationController!.topViewController?.classForCoder)!) 

if name == name2 { 
print("same view controller") 
}else { 
print("different view controller") 

} 
+0

你甚至可以重写'=='操作符来进行正确的比较。如果两个viewController属于同一个类,这并不意味着它们是平等的 –

相关问题