Skip to content

Commit 0911b40

Browse files
committed
[QuerySet] Add a method to check if a query returns any results
1 parent 2b016a0 commit 0911b40

File tree

2 files changed

+27
-0
lines changed

2 files changed

+27
-0
lines changed

QueryKit/QuerySet.swift

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -170,6 +170,21 @@ public class QuerySet<T : NSManagedObject> : SequenceType, Equatable {
170170
return count().count
171171
}
172172

173+
// MARK: Exists
174+
175+
/** Returns true if the QuerySet contains any results, and false if not.
176+
:note: Returns nil if the operation could not be completed.
177+
*/
178+
public func exists() -> Bool? {
179+
let result:Int? = count()
180+
181+
if let result = result {
182+
return result > 0
183+
}
184+
185+
return nil
186+
}
187+
173188
// MARK: Deletion
174189

175190
/// Deletes all the objects matching the QuerySet.

QueryKitTests/QuerySetTests.swift

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -179,6 +179,18 @@ class QuerySetTests: XCTestCase {
179179
XCTAssertEqual(count!, 2)
180180
}
181181

182+
// MARK: Exists
183+
184+
func testExistsReturnsTrueWithMatchingObjects() {
185+
let qs = queryset.filter(NSPredicate(format: "name == %@", "Kyle"))
186+
XCTAssertTrue(qs.exists()!)
187+
}
188+
189+
func testExistsReturnsFalseWithNoMatchingObjects() {
190+
let qs = queryset.filter(NSPredicate(format: "name == %@", "None"))
191+
XCTAssertFalse(qs.exists()!)
192+
}
193+
182194
// MARK: Deletion
183195

184196
func testDelete() {

0 commit comments

Comments
 (0)