如何在Swift中恢复堆栈跟踪?

时间:2015-07-13 22:25:01

标签: swift

如何在Swift中恢复堆栈跟踪,以便我可以找出在崩溃之前调用的最后一个方法?

我想在Swift中复制的是C#中的这个方法:

public static Assembly GetComponentInInvocationDegree(int invocationDegree)
    {
        if (invocationDegree < 0) throw new ArgumentOutOfRangeException("Cannot set out of range value: invocation degree must be greater than or equal to zero");

        var stackInvocacion = new StackTrace().GetFrames();
        if (invocationDegree > 0)
        {
            int invokingAssemblyIndex = 0;
            string currentDegreeComponentName;
            try
            {
                for (int currentDegree = 0; currentDegree < invocationDegree; currentDegree++)
                {
                    currentDegreeComponentName = stackInvocacion[invokingAssemblyIndex].GetMethod().ReflectedType.Assembly.GetName().Name;
                    while (stackInvocacion[invokingAssemblyIndex].GetMethod().ReflectedType.Assembly.GetName().Name == currentDegreeComponentName) invokingAssemblyIndex++;                        
                }
            }
            catch (Exception ex) { throw new InvalidOperationException(string.Format("Cannot get component in invocation degree: invocation degree {0} does not exist", invocationDegree), ex); }

            return stackInvocacion[invokingAssemblyIndex].GetMethod().ReflectedType.Assembly;
        }

        return stackInvocacion[0].GetMethod().ReflectedType.Assembly;
    }

2 个答案:

答案 0 :(得分:4)

在许多情况下,您可以使用try/catch机制。

do {
    try ... // risky business goes here
} catch let error as NSError {
    print("Error: \(error.domain)")
    println(NSThread.callStackSymbols())
}     

答案 1 :(得分:0)

在 swift 中,你可以这样做:

do {
    //....
}
catch {
    print("error occurred")
    print(Thread.callStackSymbols)
}