let names = ["John", "Alice", "Jack", "Bob"] let predicate = NSPredicate(format: "SELF BEGINSWITH[c] %@", "J") let filtered = (names as NSArray).filtered(using: predicate) as! [String] print(filtered)
Look for the predicate that matches names starting with 'J' ignoring case.
The predicate "SELF BEGINSWITH[c] %@" with argument "J" filters strings starting with 'J' case-insensitively. So only "John" and "Jack" remain.
let numbers = [3, 1, 4, 2] let sortDescriptor = NSSortDescriptor(key: nil, ascending: false) let sorted = (numbers as NSArray).sortedArray(using: [sortDescriptor]) as! [Int] print(sorted)
Check the ascending parameter to get descending order.
Setting ascending to false sorts the array from highest to lowest.
let predicate = NSPredicate(format: "age > %@", NSNumber(value: 18)) let filtered = people.filter { predicate.evaluate(with: $0) }
Check the placeholder %@ and the type of argument passed.
The %@ placeholder expects an object like NSNumber, but 18 is a primitive Int. This mismatch causes NSInvalidArgumentException.
Think about how multiple sort descriptors combine sorting criteria.
Multiple NSSortDescriptors apply sorting in order: first by last name, then by first name for ties.
Consider performance and data transfer when fetching from Core Data.
NSPredicate filters data at the persistent store level during fetch, reducing memory usage and improving performance.