Swift:如何创建具有Int值的谓词?
我在此语句中收到EXC-BAD-ACCESS错误:Swift:如何创建具有Int值的谓词?,swift,core-data,xcode6,Swift,Core Data,Xcode6,我在此语句中收到EXC-BAD-ACCESS错误: var thisPredicate = NSPredicate(format: "(sectionNumber == %@"), thisSection) thisSection的Int值为1,当我将鼠标悬停在其上时显示值1。但在调试区域,我看到了以下内容: thisPredicate = (_ContiguousArrayStorage ...) 另一个使用字符串的谓词显示为ObjectiveC.NSObject 为什么会发生这种情况?当
var thisPredicate = NSPredicate(format: "(sectionNumber == %@"), thisSection)
thisSection的Int值为1,当我将鼠标悬停在其上时显示值1。但在调试区域,我看到了以下内容:
thisPredicate = (_ContiguousArrayStorage ...)
另一个使用字符串的谓词显示为ObjectiveC.NSObject
为什么会发生这种情况?当数据安全或经过消毒后,您可以尝试使用字符串插值。看起来是这样的:
let thisSection = 1
let thisPredicate = NSPredicate(format: "sectionNumber == \(thisSection)")
您需要更改
%i
的%@
,并删除额外的括号:
这里的主要问题是,您正在将一个Int
放在它需要字符串的地方
以下是一个基于此的示例:
另一种解决方法是将此节的值设置为字符串
,这可以通过字符串插值或通过Int
的描述
属性来实现。。让我们说:
更改:
let thisPredicate = NSPredicate(format: "age == %i", thisSection)
为了
或
当然,您可以绕过此步骤,选择更硬的编码(但也是正确的),如:
但考虑到一些奇怪的原因
字符串插值(这种结构:“\(thisSection)”
),其中导致如上所述的保留周期
在64位体系结构上,Int
映射到Int64
,如果其值大于2147483648,%i将溢出
您需要更改%ld的%@并删除额外的括号。您有一个额外的左括号,但不应该在那里。我不确定为什么它会在上面显示一个额外的括号,因为我没有这样的括号-即:var thisPredicate=NSPredicate(格式:“(sectionNumber=%@)”,thisSection)@帕特里夏你的问题是你错过了@之后的结束括号。顺便说一句,我已经编辑了我以前的答案,也许你应该看看我添加的一些注意事项。雨果,我在上面的评论中更正了我的代码,但我没有编辑它。。。雨果,谢谢你的建议。我尝试%@但不知道如何使用。说明。我尝试了%d,但没有尝试%I。。description
是Swift中每种数据类型的属性,它将Number
、Date
等的值转换为其字符串
表示形式<代码>%i
为您执行此转换。花两天时间找出我的带谓词的fetchedresultcontroller不工作的原因,解决方案是将%@
替换为%i
。数据类型很重要,我们需要确保使用正确的类型进行筛选!!!如果值为int64%,则此操作无效。我将转换为int32,如果值高于2147483648,则将溢出。请不要在创建谓词时使用字符串插值。这个答案:,由雨果·阿隆索提供,应该被选为正确答案。那么我们应该使用什么呢??
let thisPredicate = NSPredicate(format: "age == %i", thisSection)
let thisPredicate = NSPredicate(format: "age == %@", thisSection.description)
let thisPredicate = NSPredicate(format: "age == %@", "\(thisSection)")
let thisPredicate = NSPredicate(format: "sectionNumber == \(thisSection)")