kob*_*ber 4 core-data ios swift
如何使用Apples新的编程语言Swift关闭Core Data中的SQLite Write ahead logging(WAL)?
在ObjC中,我曾经在选项字典中传入键值对@"journal_mode":@"DELETE":
[storeCoordinator addPersistentStoreWithType:NSSQLiteStoreType
configuration:nil
URL:[self databaseURL]
options:@{NSMigratePersistentStoresAutomaticallyOption: @YES,
NSInferMappingModelAutomaticallyOption: @YES,
@"journal_mode": @"DELETE"}
error:&error]
Run Code Online (Sandbox Code Playgroud)
但是在Swift中,NSDictionary中只允许相同的类型,因此混合BOOL(映射到NSNumber)和NSString是不可能的.
有任何想法吗?
这些答案很接近,但实际上对我来说都没有.以下工作正常.该选项必须与a一样NSSQLitePragmasOption.
var options = Dictionary<NSObject, AnyObject>()
options[NSMigratePersistentStoresAutomaticallyOption] = true
options[NSInferMappingModelAutomaticallyOption] = true
options[NSSQLitePragmasOption] = ["journal_mode" : "DELETE"]
if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: options, error: &error) == nil {
...
}
Run Code Online (Sandbox Code Playgroud)
默认情况下,Swift词典是强类型的,但您可以定义词典应接受的类型.
var options = Dictionary<NSObject, AnyObject>()
options[NSMigratePersistentStoresAutomaticallyOption] = true
options[NSInferMappingModelAutomaticallyOption] = true
options["journal_mode"] = "DELETE"
[storeCoordinator addPersistentStoreWithType:NSSQLiteStoreType
configuration:nil
URL:[self databaseURL]
options:opitons
error:&error]
Run Code Online (Sandbox Code Playgroud)
如果您不确定函数期望的字典类型,请查看函数声明:
func addPersistentStoreWithType(_ storeType: String!,
configuration configuration: String!,
URL storeURL: NSURL!,
options options: [NSObject : AnyObject]!,
error error: AutoreleasingUnsafePointer<NSError?>) -> NSPersistentStore!
Run Code Online (Sandbox Code Playgroud)
它准确描述了它所期望的字典类型 - Dictionary<NSObject, AnyObject>.
事实上,任何从Objective-C桥接的字典都将以这种方式输入.来自Apple Docs:
Swift还自动在Dictionary类型和NSDictionary类之间架起桥梁.当您从NSDictionary对象桥接到Swift词典时,生成的字典的类型为[NSObject:AnyObject].
您可以将任何NSDictionary对象桥接到Swift字典,因为所有Objective-C对象都是AnyObject兼容的.回想一下,如果一个对象是Objective-C或Swift类的实例,或者它可以桥接到一个对象,则该对象是AnyObject兼容的.所有NSDictionary对象都可以桥接到Swift词典,因此Swift编译器在导入Objective-C API时用[NSObject:AnyObject]替换NSDictionary类.
同样,当您在Objective-C代码中使用Swift类或协议时,导入器将与Objective-C兼容的Swift字典重新映射为NSDictionary对象.
| 归档时间: |
|
| 查看次数: |
2452 次 |
| 最近记录: |