[英]Swift accessing app delegate through test cases raises swift_dynamiccast unconditional exception
I am getting swift_dynamiccast unconditional exception while accessing app delegate from test cases in one of the methods in application. 在应用程序中的一种方法中,从测试用例访问应用程序委托时,我遇到了swift_dynamiccast无条件异常。
The function in the application is like this: 应用程序中的功能如下:
func sampleMethod()
{
var appdelegate:AppDelegate = UIApplication.sharedApplication().delegate! as AppDelegate
}
Test case is accessing this method as: 测试用例按以下方式访问此方法:
func testStart()
{
var sample:MyClass = MyClass()
sample.sampleMethod()
}
It is raising exception in the method sampleMethod(), then it goes ahead. 它在sampleMethod()方法中引发异常,然后继续。 I have added MyClass & AppDelegate files in the test case project in build phases.
我已经在构建阶段的测试用例项目中添加了MyClass&AppDelegate文件。
Any suggestions whats wrong here? 有什么建议怎么了吗? A similar unanswered question here.
这里有一个类似的未解决问题。
Did you add AppDelegate.swift to the test's target members? 您是否将AppDelegate.swift添加到测试的目标成员?
Instead, try importing it from your application module. 而是尝试从您的应用程序模块导入它。
And Rick's right. 里克是对的。 I faced a similar problem, solved it after going through
我遇到了类似的问题,经过检查解决了
UIApplication.sharedApplication().delegate as AppDelegate causes EXC_BAD_ACCESS using it on swift unit test UIApplication.sharedApplication()。delegate作为AppDelegate导致EXC_BAD_ACCESS在快速单元测试中使用它
This is because AppDelegate object in the case of tests is different type than main project AppDelegate. 这是因为在测试情况下,AppDelegate对象的类型与主项目AppDelegate的类型不同。 Because of this your app is crash
因此,您的应用崩溃了
class MyClass: NSObject {
func someMethod() {
var checkObject:AnyObject = UIApplication.sharedApplication().delegate!;
NSLog("%@", checkObject.description);
var appdelegate:AppDelegate = AppDelegate();
NSLog("%@", appdelegate);
}
}
You can see result of this function in console: 您可以在控制台中看到此功能的结果:
2015-01-14 13:03:58.299 TestSwift[654:282510] <TestSwift.AppDelegate: 0x17007b940>
2015-01-14 13:04:01.085 TestSwift[654:282510] <TestSwiftTests.AppDelegate: 0x17467f740>
Possible solution: use AnyObject variable instead of casting to AppDelegate 可能的解决方案:使用AnyObject变量而不是强制转换为AppDelegate
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.