iOS 개발 NSPredicate

3605 단어
Predicate는 흔히'술어'로 번역된다. 이것은 한 대상의 성질이나 대상 간의 상호 관계를 묘사하는 데 사용된다. 예를 들어'소명은 프로그래머다'라는 문장의'프로그래머'가 바로 술어이다.코코아에서 NSPredicate는 대상의 성질이나 상호 관계에 따라 논리적으로 판단할 수 있는 도구다.
개념만 보면 이해가 잘 안 돼서 코드를 바로 올립니다.
NSPredicate *isRich = [NSPredicate predicateWithFormat:@"account.balance > 5000000"];

Person *zhangSan = [[Person alloc] initWithName:@"ZhangSan" andBalance:9999];
Person *bill = [[Person alloc] initWithName:@"Bill" andBalance:1000000000];

NSLog(@"%d", [isRich evaluateWithObject:zhangSan]);  //   0
NSLog(@"%d", [isRich evaluateWithObject:bill]);  //   1

NSPredicate 객체 만들기
위의 예에서 보듯이 우리는 NSPredicate가 제공하는 클래스 방법을 통해 포맷 문자열로 NSPredicate 대상을 편리하게 만들 수 있다.
코코아는 문자열을 포맷하기 위해 풍부한 문법 지원을 제공합니다: 비교 연산자:, >=, =,!=,BETWEEN
[NSPredicate predicateWithFormat:@"account.balance > 5000000"];
[NSPredicate predicateWithFormat:@"account.balance BETWEEN {100, 1000}"];

복합 연산자: OR, AND 및 NOT
[NSPredicate predicateWithFormat:@"startDate <= %@ AND endDate >= %@", now, now];

문자열 판단: BEGINSWITH, CONTAINS, ENDSWITH, LIKE, MATCHES
[NSPredicate predicateWithFormat:@"name BEGINSWITH 'Zhang'" ];
[NSPredicate predicateWithFormat:@"name CONTAINS 'ang'" ];
// LIKE     ,*       ,?        
[NSPredicate predicateWithFormat:@"url LIKE 'https://*.taobao.com*'" ];
// MATCHES       
NSString *regex = @"[0-9]*"; 
[NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];

컬렉션 연산: ANY, SOME, ALL, NONE, IN
NSArray *names = @[@"ZhangSan", @"LiSi", @"WangWu"];
NSPredicate *anyIsZhang = [NSPredicate predicateWithFormat:@"ANY SELF BEGINSWITH 'Zhang'" ];
NSLog(@"%d", [anyIsZhang evaluateWithObject:names]);

상수 및 자리 표시자:%@,%k, SELF
//            ,           ,       
//    name BEGINSWITH 'Zhang'         ,name   ,Zhang   

//                    ,                   
[NSPredicate predicateWithFormat:@"name BEGINSWITH %@", familyName];

//       , %@      ,         
// "name BEGINSWITH %@"     "name BEGINSWITH 'familyName'"
//   %@          。
//                ,        :
[NSPredicate predicateWithFormat:@"%k BEGINSWITH %@", propertyName, familyName];

//              %@       ,               :
predicate = [NSPredicate predicateWithFormat:@"SELF like %@*%@", prefix, suffix];
ok = [predicate evaluateWithObject:@"prefixxxxxxsuffix"];

코코아는 위에서 언급한 포맷 문자열을 사용하여 NSPredicate를 만드는 방법을 제외하고는 NSPredicate를 만드는 두 가지 방법을 제공했다.그것들의 문법은 상대적으로 복잡하기 때문에 여기서는 군말이 많지 않다.
NSPredicate 객체 사용
NSPredicate의 가장 기본적인 사용법은 NSPredicate 대상을 만들어서 판단할 대상을 전달하는 것이다. evaluateWithObject: 방법으로 판단하는 것이다.
NSPredicate *isRich = [NSPredicate predicateWithFormat:@"account.balance > 5000000"];
Person *zhangSan = [[Person alloc] initWithName:@"ZhangSan" andBalance:9999];
NSLog(@"%d", [isRich evaluateWithObject:zhangSan]);  //   0

또한 NSPredicate를 컬렉션 필터로 사용할 수도 있습니다.
NSArray *names = @[@"ZhangSan", @"LiSi", @"WangWu"];
NSPredicate *containsN = [NSPredicate predicateWithFormat:@"SELF CONTAINS 'n'" ];
NSLog(@"%@", [names filteredArrayUsingPredicate:containsN]); //   ["ZhangSan", "WangWu"]

참고 자료
Predicate Programming Guide

좋은 웹페이지 즐겨찾기