Search and query IOS NSPredicate

Source: Internet
Author: User

Brief description: NSPredicate in the Cocoa framework is used for queries. Its principles and usage are similar to where in SQL, and its function is equivalent to database filtering.

The most common functions

+ (NSPredicate *)predicateWithFormat:(NSString *)predicateFormat, ...;

1. Comparison operators>, <, =, >=, <=, and ,! =
Example: @ "number> = 99"

 

2. Range operators: IN and
Example: @ "number BETWEEN {1, 5 }"
@ "Address IN {'shanghai', 'nanjing '}"

3. string itself: SELF
Example: @ "SELF = 'apple '"

4. String-related: BEGINSWITH, ENDSWITH, and CONTAINS
Example: @ "name CONTAIN [cd] 'ang '" // contains a string
@ "Name BEGINSWITH [c] 'sh'" // starts with a string
@ "Name ENDSWITH [d] 'ang '" // end with a string
Note: [c] is case-insensitive, and [d] is case-insensitive. That is, there is no accent. [cd] is case-insensitive and does not distinguish between pronunciation symbols.

5. wildcard: LIKE
For example, @ "name LIKE [cd] '* er *'" // * Indicates a wildcard, and Like also accepts [cd].
@ "Name LIKE [cd] '??? Er *'"

 

6. Regular Expression: MATCHES
For example, NSString * regex = @ "^ A. + e $"; // starts with A and ends with e.
@ "Name MATCHES % @", regex

 

Practical Application: filtering NSArray

NSArray *array = [[NSArray alloc]initWithObjects:@"beijing",@"shanghai",@"guangzou",@"wuhan", nil];  NSString *string = @"ang";  NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF CONTAINS %@",string];  NSLog(@"%@",[array filteredArrayUsingPredicate:pred]);  

 

Practical Application: Determine whether the first letter of a string is a letter

NSString *regex = @"[A-Za-z]+";  NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];    if ([predicate evaluateWithObject:aString]) {  }  

 

Practical Application: String replacement

NSError* error = NULL;  NSRegularExpression* regex = [NSRegularExpression regularExpressionWithPattern:@"(encoding=\")[^\"]+(\")"                                                                              options:0                                                                              error:&error];  NSString* sample = @"<xml encoding=\"abc\"></xml><xml encoding=\"def\"></xml><xml encoding=\"ttt\"></xml>";  NSLog(@"Start:%@",sample);  NSString* result = [regex stringByReplacingMatchesInString:sample                                                        options:0                                                         range:NSMakeRange(0, sample.length)                                                        withTemplate:@"$1utf-8$2"];  NSLog(@"Result:%@", result);  

 

Practical Application: intercepting strings

// Assemble a string, you need to parse the URL NSString * urlString = @ "<meta/> <link/> <title> 1Q84 BOOK1 </title> 

 

Practical Application: mobile phone number and phone number Function

// Regular expression to determine the mobile phone number address format-(BOOL) isMobileNumber :( NSString *) mobileNum {/*** mobile phone number *: 134 [0-8], 135,136,137,138,139,150,151,157,158,159,182,187,188 * Unicom: 130,131,132,152,155,156,185,186 * China Telecom: 133,1349, 153,180,189 */NSString * MOBILE = @ "^ 1 (3 [0-9] | 5 [0-35-9] | 8 [025-9]) \ d {8} $ ";/** 10 * China Mobile: China Mobile 11*134 [0-8], 135,136,137,138,139,150,151,157,158,159,182,187,188 12 */NSString * CM = @ "^ 1 (34 [0-8] | (3 [5-9] | 5 [017-9] | 8 [278]) \ d) \ d {7} $ ";/** 15 * China Unicom: china Unicom 16*130,131,132,152,155,156,185,186 17 */NSString * CU = @ "^ 1 (3 [0-2] | 5 [1, 256] | 8 [56]) \ d {8} $ ";/** 20 * China Telecom: China Telecom 21*133,1349, 153,180,189 22 */NSString * CT = @ "^ 1 (33 | 53 | 8 [09]) [0-9] | 349) \ d {7} $ "; /** 25 * fixed lines in mainland China and PHS 26 * area code: 010,020,021,022,023,024,025,027,028,029 27 * No: seven or eight digits 28 * // NSString * PHS = @ "^ 0 (10 | 2 [0-5789] | \ d {3 }) \ d {7,8} $ "; NSPredicate * regextestmobile = [NSPredicate response: @" self matches % @ ", MOBILE]; NSPredicate * regextestcm = [NSPredicate predicateWithFormat: @ "self matches % @", CM]; NSPredicate * regextestcu = [NSPredicate predicateWithFormat: @ "self matches % @", CU]; NSPredicate * regextestct = [NSPredicate response: @ "self matches % @", CT]; if ([regextestmobile evaluateWithObject: mobileNum] = YES) | ([regextestcm evaluateWithObject: mobileNum] = YES) | ([regextestct failed: mobileNum] = YES) | ([regextestcu evaluateWithObject: mobileNum] = YES) {if ([regextestcm evaluateWithObject: mobileNum] = YES) {NSLog (@ "China Mobile");} else if ([regextestct evaluateWithObject: mobileNum] = YES) {NSLog (@ "China Telecom ");} else if ([regextestcu evaluateWithObject: mobileNum] = YES) {NSLog (@ "China Unicom");} else {NSLog (@ "Unknow");} return YES ;} else {return NO ;}}

 

Practical Application: email verification and phone number verification

// Whether it is a valid regular expression + (BOOL) isValidateRegularExpression :( NSString *) strDestination byExpression :( NSString *) strExpression {NSPredicate * predicate = [identifier: @ "self matches % @", strExpression]; return [predicate evaluateWithObject: strDestination];} // verify email + (BOOL) isValidateEmail :( NSString *) email {NSString * strRegex = @ "[A-Z0-9a-z. _ % +-] + @ [A-Za-z0-9. -] + \\. [A-Za-z] {1, 5} "; BOOL rt = [CommonTools isValidateRegularExpression: email byExpression: strRegex]; return rt;} // verify the phone number + (BOOL) isValidateTelNumber :( NSString *) number {NSString * strRegex = @ "[0-9] {1, 20}"; BOOL rt = [CommonTools isValidateRegularExpression: number byExpression: strRegex]; return rt ;}

 

Practical Application: NSDate for filtering

// Within ten days: NSDate * endDate = [[NSDate date] retain]; NSTimeInterval timeInterval = [endDate timeIntervalSinceReferenceDate]; timeInterval-= 3600*24*10; NSDate * beginDate = [[NSDate Duration: timeInterval] retain]; // filter coredata (assuming fetchRequest is available) NSPredicate * predicate_date = [NSPredicate predicateWithFormat: @ "date >=% @ AND date <= % @", beginDate, endDate]; [fetchRequest setPredicate: predicate_date]; // release retained object [endDate release]; [beginDate release];
Related Article

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.