尝试保存gamedata时出错

时间:2015-11-19 14:18:21

标签: ios swift swift2 plist

我试图保存游戏数据

    if !fileManager.fileExistsAtPath(path) {
        // create an empty file if it doesn't exist
        if let bundle = NSBundle.mainBundle().pathForResource("DefaultFile", ofType: "plist") {
            fileManager.copyItemAtPath(bundle, toPath: path)
        }
    }

但是得到了错误:通话可以抛出,但没有标记为'尝试'并且没有处理错误。

该变体应该在Swift中工作,但不适用于Swift2 .. 如何修改代码?

2 个答案:

答案 0 :(得分:1)

你需要使用Swifts new try catch

if (!fileManager.fileExistsAtPath(path)) {
    // create an empty file if it doesn't exist
    if let bundle = NSBundle.mainBundle().pathForResource("DefaultFile", ofType: "plist") {
        do {
            try fileManager.copyItemAtPath(bundle, toPath: path)
        } catch {
            //Catch Error Here
        }

    }
}

这可以解决你的问题,如果不是只写我: - )

答案 1 :(得分:0)

错误原因

  

通话可以抛出,但未标记为'尝试

是因为,方法

public func copyItemAtPath(srcPath: String, toPath dstPath: String) throws

表示您使用的方法可能会抛出错误(请参阅throws关键字?),因此编译器会指示您使用swift try catch方法捕获错误

if !fileManager.fileExistsAtPath(path) {
// create an empty file if it doesn't exist
if let bundle = NSBundle.mainBundle().pathForResource("DefaultFile", ofType: "plist") {
             do  {
                try fileManager.copyItemAtPath(bundle, toPath: path)
             }
             catch {
                //Catch error here
             }
        }
    }