NSPredicate to test for NULL, and blank strings
If you don't use Core Data, you could do:
NSPredicate *predicateName = [NSPredicate predicateWithFormat:@"name.length > 0"];
If the string is empty, this will fail (because 0 == 0
). Similarly, if name
is nil
, it will also fail, because [nil length] == 0
.
NSPredicate to check for NULL, and blank strings in Core Data
Please go through CoreData predicate: string property length?
or you can do like this
NSString *attributeName = @"name";
NSString *attributeValue = [NSString stringWithFormat:@".{%d}", 5];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"%K MATCHES %@", attributeName, attributeValue];
Reference - NSPredicate for an NSManagedObject's string attribute's length
NSPredicate in swift for empty string
You can simply compare to the empty String
, ""
. The %@
placeholder represents a String
, so the crash happens because you supply an Int
to the NSPredicate
instead of a String
.
You should also use the %K
placeholder for variable names instead of appending strings.
let predicate = NSPredicate(format: " %K != %@", remoteAttributes.lineOwner, "")
If you also want to filter out nil
values, you can use a compound predicate:
let predicate = NSPredicate(format: " %K != %@ AND %K != nil", remoteAttributes.lineOwner, "")
Generic is null predicate]
Since isNull()
is generic, and the compiler cannot infer the generic parameter when combined like that, you need to explicitly specify the type parameter.
To do that, you must qualify with the class name, e.g. Test
:
Test.<String>isNull().or(isEmpty())
Full example:
public class Test {
public static void main(String[] args) {
Predicate<String> isNullOrEmpty = Test.<String>isNull().or(isEmpty());
System.out.println(isNullOrEmpty.test(null)); // true
System.out.println(isNullOrEmpty.test("")); // true
System.out.println(isNullOrEmpty.test("Foo")); // false
}
private static <T> Predicate<T> isNull(){
return Objects::isNull;
}
private static Predicate<String> isEmpty(){
return string -> string.isEmpty();
}
}
You can also resolved it by assigning each part to a variable:
Predicate<String> isNull = isNull(); // String is inferred from assignment operator
Predicate<String> isEmpty = isEmpty();
Predicate<String> isNullOrEmpty = isNull.or(isEmpty);
Or just the first part:
Predicate<String> isNull = isNull();
Predicate<String> isNullOrEmpty = isNull.or(isEmpty());
How to create NSCompoundPredicate with empty predicate
Instead of creating “empty” predicates you can dynamically build an array containing only the needed predicates:
var predicates = [NSPredicate]() // Start with empty list.
if isGenreFilterOn {
// Add genre predicate:
predicates.append(NSPredicate(format: "genID == \(genreID)"))
}
if !searchFor.isEmpty {
// Add book predicate:
predicates.append(NSPredicate(format: "bokName CONTAINS[cd] %@", searchFor))
}
// ... more criteria ...
// Combine all predicates:
let predicate = NSCompoundPredicate(type: .and, subpredicates: predicates)
More optional (or non-optional) criteria can easily be added. This works correctly even if the predicates array is empty.
Remark: Be careful with string interpolation in predicate format strings.
NSPredicate(format: "genID == \(genreID)")
is fine if genreID
is a number, but can crash at runtime if it is a string and contains any special characters or reserved keywords for predicates.
NSPredicate for an NSManagedObject's string attribute's length
Not sure how this code snippet is performance wise but here is my answer to your question:
NSString *attributeName = @"letters";
NSString *attributeValue = [NSString stringWithFormat:@"'.{%d,%d}'", 5, 20];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"%K MATCHES %@", attributeName, attributeValue];
[fetchRequest setPredicate:predicate];
Joss.
iOS - NSPredicate string.length always evaluates to 0 when string starts with arithmetic operators + - * /
You cannot use Objective-C functions like length
in a Core Data fetch request
(and the ".length" part is simply ignored when Core Data translates the fetch request
to a SQLite query). But you can simply compare with an empty string instead:
[NSPredicate predicateWithFormat:@"comment != ''"]
For other queries involving the length, you can use the MATCHES operator with
a regular expression as shown here: CoreData predicate: string property length?.
Related Topics
Cagradientlayer Diagonal Gradient
How to Change the Uisearchbar Search Text Color
How to Add Constraint Between a View and the Top Layout Guide in a Xib File
Uiscrollview's Origin Changes After Popping Back to the Uiviewcontroller
What's Dead & Exploded in Swift's Exception Stack
Facebook Share Content Only Shares Url in iOS 9
Adding Background Image to Uilabel
Accessing Core Data SQL Database in iOS 8 Extension (Sharing Data Between App and Widget Extension)
Extracting H264 from Cmblockbuffer
iOS How to Asynchronously Download and Cache Images and Videos for Use in My App
Uinavigationcontroller Without Navigation Bar
How to Solve "Error Running Pod Install" in Flutter on MAC
Alternative Ways to Push View Controllers with Storyboard Programmatically
How to Add Headerview in Uicollectionview Like Uitableview's Tableheaderview
Change Order of Read Items with Voiceover
Wait for Async Task to Finish Completion Block Before Returning in App Delegate