iOS 개발 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
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
다양한 언어의 JSONJSON은 Javascript 표기법을 사용하여 데이터 구조를 레이아웃하는 데이터 형식입니다. 그러나 Javascript가 코드에서 이러한 구조를 나타낼 수 있는 유일한 언어는 아닙니다. 저는 일반적으로 '객체'{}...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.