在 App-Group 文件夹中创建领域文件在 WatchOS(WatchKit 扩展)下不起作用

creation of realm file in App-Group Folder does not work under WatchOS (WatchKit Extension)

以下代码在 iOS-8.x / Swift-1.2 / WatchKit-1.0

下工作
    // create Realm_DB-File in shared App-Groups Folder
    let directory: NSURL = NSFileManager.defaultManager().containerURLForSecurityApplicationGroupIdentifier(AppConstants.APP_GROUP_IDENTIFIER_KEY)!
    let realmPath = directory.path!.stringByAppendingPathComponent(AppConstants.REALM_FILENAME_KEY)
    playerRealm = Realm.init(path: realmPath)

但在iOS-9.0.1 / Swift-2.0 / WatchOS-2.0

下不可用

两条错误信息是:

1.) 'stringByAppendingPatchComponent' 不可用:改用 NSURL 上的 URLByAppendingPathComponent

2.)调用可以抛出,但是没有标记'try',错误没有处理

感谢任何帮助!

要解决您的第一个问题,您需要投射:

directory.path as NSString

因为路径作为 String 返回,在 Swift 中不提供 stringByAppendingPathComponent 方法。

其次,Swift 2.0 有新的错误处理,因此可以抛出错误的方法被标记为 throws。然后,这些方法要求您在调用前添加 try。请参阅 Apple 的相关文档:Swift Error Handling

如果您知道路径保证有效,要禁用错误处理,您可以简单地写:

playerRealm = try! Realm(path: realmPath)