2016-06-22 15 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屬於同一個類,這並不意味着它們是平等的 –

相關問題