当我尝试执行CoreData提取请求时,我得到正确的行数。
let req = Track.fetchRequest()
return try context.count(for: req)
// result: 81
有效:
当我尝试添加bool条件时,
let req = Track.fetchRequest()
req.predicate = NSPredicate(format: "isSentToServer = NO")
return try context.count(for: req)
// result: 0
不是。结果无论我尝试什么,它总是 0 (但仍然应该是 81 ):
NSPredicate(format: "isSentToServer = %i", NSNumber(value: false))
NSPredicate(format: "isSentToServer = %@", NSNumber(value: false))
NSPredicate(format: "isSentToServer = 0")
NSPredicate(format: "isSentToServer = %@", false)
NSPredicate(format: "isSentToServer = %@", 0)
NSPredicate(format: "isSentToServer != YES")
NSPredicate(format: "isSentToServer == NO")
NSPredicate(format: "isSentToServer == %@", "NO")
注意:isSentToServer
是一个正确识别的属性,更改大小写或添加Z
将无济于事。
大量的Swift教程作者不知道有什么变化吗?
编辑:Track
类是由Core Model实体编辑器自动生成的,其类型为Bool
(编辑器中为“ Boolean”)(不是Bool?
)
更新
以下是我的测试代码中的输出,其中包含建议的-com.apple.CoreData.SQLDebug 1
(谓词:isSentToServer != YES
):
CoreData: sql: SELECT TBL_NAME FROM SQLITE_MASTER WHERE TBL_NAME = 'Z_METADATA'
CoreData: sql: pragma recursive_triggers=1
CoreData: sql: pragma journal_mode=wal
CoreData: sql: SELECT Z_VERSION, Z_UUID, Z_PLIST FROM Z_METADATA
CoreData: sql: SELECT TBL_NAME FROM SQLITE_MASTER WHERE TBL_NAME = 'Z_METADATA'
CoreData: sql: SELECT TBL_NAME FROM SQLITE_MASTER WHERE TBL_NAME = 'Z_MODELCACHE'
CoreData: sql: SELECT TBL_NAME FROM SQLITE_MASTER WHERE TBL_NAME = 'ACHANGE'
CoreData: sql: SELECT COUNT(*) FROM ZTRACK
CoreData: annotation: total count request execution time: 0.0004s for count of 90.
Total track objects: 90
CoreData: sql: SELECT COUNT( DISTINCT t0.Z_PK) FROM ZTRACK t0 WHERE t0.ZISSENTTOSERVER <> ?
CoreData: annotation: total count request execution time: 0.0005s for count of 0.
Track objects pending upload: 0
对于= NO
和其他“相等”的情况,它会生成SQL "= ?"
如何创建Track
对象?
let track = Track(context: context) // context is from AppDelegate, auto-generated by Xcode
// set up some properties
// not assigning any isSentToServer value explicitly
context.save() // no errors
编辑2:注意,我已经在Xcode中尝试了iPhone 6模拟器的“擦除数据”,并重新创建了Track对象,但第二个请求仍返回零行计数。
Xcode:版本10.2(10E125)
定位iOS SDK /版本:11.0或12.2,没有区别
$ xcodebuild -showsdks
iOS SDKs:
iOS 12.2 -sdk iphoneos12.2
iOS Simulator SDKs:
Simulator - iOS 12.2 -sdk iphonesimulator12.2
答案 0 :(得分:0)
这是具有解决方法的评论。
帮助的是以下各项的组合:
track.isSentToServer = false
为 new 对象完全 track.time = Date()
(我不在谓词中使用此字段)(生成的类型为:Date?
)因此,谓词起作用。
尽管如此,我的期望还是很合理的:
false
必须是默认类型,因为它具有Bool
类型(不是Bool?
)。 nil
必须是Date?
属性的默认值,并且不得影响未提及该属性的谓词。我无法找到有关此行为是否已记录的信息。