Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
924 views
in Technique[技术] by (71.8m points)

core data - Can I use an NSPredicate in Swift with a nil argument?

I'm trying to convert a project that uses Core Data from Objective-C to Swift.

The data model is structured so that I have one master folder which contains other folders - and those folders can also contain other folders, via a "parentFolder" relationship.

Currently, I do this in Objective-C to retrieve the master folder (it finds the only folder without a "parentFolder", and works as expected):

NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:"Folder"];
request.predicate = [NSPredicate predicateWithFormat:@"parentFolder == %@", nil];

In converting to Swift, I'd like to do the same thing:

let request = NSFetchRequest(entityName: "Folder")
request.predicate = NSPredicate(format: "parentFolder == %@", nil)

... but the compiler complains with "Missing argument label 'argumentArray:' in call. (I seem to be confusing it into thinking I need to use the NSPredicate(format: argumentArray:) method instead...)

Is there a correct way to do this in Swift?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It looks as if it is (with the current Xcode 6 beta 3 release) generally difficult to pass nil in a variable argument list.

This seems to work:

let predicate = NSPredicate(format: "parentFolder == %@", 0)
print(predicate)
// Output: parentFolder == nil

But the easiest solution would be to simply write the predicate as

NSPredicate(format: "parentFolder == nil")

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...