iOS Development-nspredicate

Source: Internet
Author: User

The COCOA predicate (predicate) provides a common query method for processing data, which can obtain and specify the filter form of the data, Cocoa actual development can be using nspredicate and its parent class nscomparisonpredicate and nscompoundpredicate. Its style is similar to the mixture of SQL query language and regular expression, providing an expressive, natural language interface to define a collection to be searched The logical condition of the search. In general, it is easy to understand how to use a database, and the method is simple.

Nspredicate in the collectionthe foundation provides a way to filter nsarray/nsmutablearray&nsset/nsmutableset using predicates (predicate). immutable collections, Nsarray&nsset, You can return an immutable collection of methods Filteredarrayusingpredicate and filteredsetusingpredicate by evaluating the received predicate;variable collection, Nsmutablearray&nsmutableset, you can use method Filterusingpredicate: You can remove an object that evaluates to False by running the received predicate.

let's start with a relatively simple code:

    Nspredicate *predicate = [Nspredicate predicatewithformat:@ "Self in%@", @[@ "Keso", @ "flyelephant", @ "blog Park"];    if ([Predicate evaluatewithobject:@ "Keso"]) {        NSLog (@ "Keso");    };

The first line of code initializes a query condition, and the second sentence is to judge that the data is not in the result set, basically the same as SQL, through in can probably understand its function, self means itself, very often.

Next can be similar to the code in SQL like statement:

   Nsarray *array = [[Nsarray alloc]initwithobjects:@ "Beijing", @ "Shanghai", @ "Guangzhou", @ "Shenzhen", nil];    Nspredicate *prebegin= [nspredicate predicatewithformat:@ "self beginswith[c]%@", @ "North"];    Nspredicate *precontain= [nspredicate predicatewithformat:@ "self contains[c]%@", @ "Sea"];        NSLog (@ "%@", [array filteredarrayusingpredicate:prebegin][0]);    NSLog (@ "%@", [array filteredarrayusingpredicate:precontain][0]);

The first is to initialize the array and then create the condition to filter the array by filteredarrayusingpredicate;

Nsdictionary can use predicates to filter its keys and values (both are Nsarray objects);

Nsorderedset can generate a new ordered set by a filtered nsarray or nsset, or nsmutableset can simply removeobjectsinarray to pass an object that is filtered by a negative predicate.

In Core data.NSPredicate

Predicates are also applicable in core data, where predicates are evaluated by the persistence Storage Assistant (persistent store coordinator) in the Management object environment, and the collection is in-memory filtering. This is where we need to know the basic comparison operators:

    • =, = =: The expression on the left is equal to the expression on the right.
    • >=, =>: The expression on the left is greater than or equal to the expression on the right.
    • <=, =<: The expression on the left is less than or equal to the right expression.
    • : The expression on the left is greater than the right expression.
    • <: The left expression is less than the right expression.
    • ! =, <>: The expression on the left is not equal to the expression on the right.
between: The expression on the left equals the value of the expression on the right or between them. On the right is a sequence of two values that specify the upper and lower bounds (the sequence of the specified order). For example, 1 between {0, 33}, or $input between {$LOWER, $UPPER}. Refer to the following code:
Nspredicate *betweenpredicate =    [nspredicate predicatewithformat: @ "AttributeName between%@", @[@1, @10]];        Nsdictionary *dictionary = @{@ "AttributeName": @5};        BOOL between = [Betweenpredicate evaluatewithobject:dictionary];    if (between) {        NSLog (@ "comparison operator between");    }
Basic COMPOUND predicate
    • And, &&: Logical AND.
    • OR, | | : Logical OR.
    • Not,!: Logical Non-
string comparisonstring comparisons are very common, and the following should be more familiar:
    • BEGINSWITH[CD] $FIRST _name.
    • Beginswith: The expression on the left begins with the expression on the right.
    • CONTAINS: The expression on the left contains the expression on the right.
    • ENDSWITH: The expression on the left ends with the expression on the right.
    • Like: The expression on the left equals the expression on the right:? and * can be used as wildcards, where? matches 1 characters, * matches 0 or more characters.
    • MATCHES: The expression on the left is compared to the regex style of ICU v3, which equals the right expression.
refer to the following code:
    NSString *regex = @ "[a-za-z]+";    Nspredicate *matchpredicate = [Nspredicate predicatewithformat:@ "Self MATCHES%@", regex];        if ([Matchpredicate evaluatewithobject:@ "Keso"]) {        NSLog (@ "match succeeded");    }
Relational Operations
    • Any,some: Specifies any element in the following expression. For example, any children.age < 18.
    • All: Specifies all elements in the following expression. For example, all Children.age < 18.
    • None: Specifies an element that is not in the following expression. For example, NONE Children.age < 18. It is logically equal to not (any ...).
    • In: equals the in operation of SQL, the left expression must appear in the collection specified on the right. For example, name in {' Ben ', ' Melissa ', ' Nick '}.
Array Manipulation
    • Array[index]: Specifies the element at a particular index in the array.
    • Array[first]: Specifies the first element in the array.
    • Array[last]: Specifies the last element in the array.
    • Array[size]: Specifies the size of the array.
Boolean predicate
    • Truepredicate: The result is always a true predicate.
    • Falsepredicate: The result is always a false predicate.
here is a simple code that uses predicates to search for class objects:Create a new people class, header file:
@interface People:nsobject@property (strong,nonatomic) nsstring *firstname; @property (strong,nonatomic) NSString * LastName, @property (nonatomic) Nsinteger height;-(NSString *) description; @end

PEOPLE.M file:

@implementation people-(NSString *) Description {    return  [nsstring stringwithformat:@ "%@%@", self. LastName, self. FirstName];}; @end

Specific implementation code:

        Nsarray *firstnames =[[nsarray alloc]initwithobjects:@ "Zedong", @ "Enlai", @ "medium stone", @ "Zhongshan", nil];    Nsarray *lastnames = @[@ "Mao", @ "Week", @ "Chiang", @ "Sun"];        Nsarray *familiar = @[@100, @99, @99, @98];    Nsmutablearray *datalist= [Nsmutablearray array]; [Firstnames enumerateobjectsusingblock:^ (id obj, Nsuinteger idx, BOOL *stop)        {People *people= [[People alloc] init]; People.        FirstName = Firstnames[idx]; People.                LastName = Lastnames[idx]; People.        height= [Familiar[idx] integervalue];    [DataList Addobject:people];        }];    Nspredicate *firstpredicate = [Nspredicate predicatewithformat:@ "FirstName = ' Enlai '"];    Nspredicate *lastpredicate = [Nspredicate predicatewithformat:@ "LastName =%@", @ "Chiang"];      Nspredicate *heightpredicate = [Nspredicate predicatewithformat:@ "Height < 99"];        Name Search NSLog (@ "Name:%@", [DataList filteredarrayusingpredicate:firstpredicate][0]); Last Name Search NSLog (@ "Surname:%@", [DataList filteredarrayusingpredicate:lastPredicate][0]); Popularity NSLog (@ "Popularity:%@", [DataList filteredarrayusingpredicate:heightpredicate][0]);

Actually started talking about theNSCompoundPredicate和NSComparisonPredicate,因为有关系操作,基本上类似,如果通过混合搜索可以使用and,or实现,比如一下代码是等价的:

   Nscompoundpredicate *compredicate=[nscompoundpredicate Andpredicatewithsubpredicates:@[[nspredicate predicatewithformat:@ "Height > All"], [nspredicate predicatewithformat:@ "FirstName =%@", @ "medium stone"]];       Nspredicate *secondpredicate=[nspredicate predicatewithformat:@ "(Height > All) and (FirstName =%@), @" Medium stone "];

Nscomparisonpredicate has two static methods of invocation:

+ (Nscomparisonpredicate *) Predicatewithleftexpression: (nsexpression *) LHS rightexpression: (NSExpression *) RHS Modifier: (nscomparisonpredicatemodifier) modifier type: (nspredicateoperatortype) type options: ( nscomparisonpredicateoptions) options;+ (nscomparisonpredicate *) Predicatewithleftexpression: (NSExpression *) LHS Rightexpression: (nsexpression *) RHS Customselector: (SEL) selector;

In fact, is an expression of the splicing process, but the specific implementation of the Apple package, the Nspredicateoperatortype type:

typedef ns_enum (Nsuinteger, Nspredicateoperatortype) { Nslessthanpredicateoperatortype = 0,//compare:returns nsorderedascending Nslessthanorequaltopredicateoperatortype, Compare:returns Nsorderedascending | | Nsorderedsame Nsgreaterthanpredicateoperatortype,//Compare:returns nsordereddescending NSGreaterThanOrEqualToPred Icateoperatortype,//compare:returns nsordereddescending | | Nsorderedsame Nsequaltopredicateoperatortype,//Isequal:returns true Nsnotequaltopredicateoperatortype,//IsEqual    : Returns False Nsmatchespredicateoperatortype, Nslikepredicateoperatortype, Nsbeginswithpredicateoperatortype, Nsendswithpredicateoperatortype, Nsinpredicateoperatortype,//RHS contains LHS returns true Nscustomselectorpredi    Cateoperatortype, Nscontainspredicateoperatortype ns_enum_available (10_5, 3_0) =,//LHS contains RHS returns true Nsbetweenpredicateoperatortype ns_enum_available (10_5, 3_0)}; 

Reference: https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/Predicates/Articles/pSyntax.html#/ /apple_ref/doc/uid/tp40001795-sw1

iOS Development-nspredicate

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.