`
啸笑天
  • 浏览: 3440374 次
  • 性别: Icon_minigender_1
  • 来自: China
社区版块
存档分类
最新评论

Objective-C NSPredicate

 
阅读更多

NSPredicate

Cocoa提供了一个NSPredicate类,它用来指定过滤器的条件

原理类似于数据库查询

17.1 创建谓词

predicateWithFormat:

NSPredicate *predicate;

predicate = [NSPredicate predicateWithFormat:@"name == 'Herbie'"];

注意:如果谓词串中的文本块未被引用,则被看做是键路径,即需要用引号表明是字符串,单引号,双引号均可.键路径可以在后台包含许多强大的功能

计算谓词:

BOOL match = [predicate evaluateWithObject:car];

让谓词通过某个对象来计算自己的值,给出BOOL值

17.2 燃料过滤器

filteredArrayUsingPredicate:是NSArray数组的一种类别方法,循环过滤数组中的内容,将值为YES的对象累积到结果数组中返回

iphone编程应该密切注意谓词使用带来的性能问题

17.3 格式说明符

%d和%@等插入数值和字符串,%K表示key

还可以引入变量名,用$,类似环境变量,如:@"name == $NAME",再用predicateWithSubstitutionVariables调用来构造新的谓词(键/值字典),其中键是变量名,值是要插入的内容,注意这种情况下不能把变量当成键路径,只能用作值

17.4 运算符

17.4.1 比较和逻辑运算符

==等于

>:大于

>=和=>:大于或等于

<:小于

<=和=<:小于或等于

!=和<>:不等于

括号和逻辑运算AND、OR、NOT或者C样式的等效表达式&&、||、!

注意:不等号适用于数字和字符串

17.4.2 数组运算符

BETWEEN和IN后加某个数组,可以用{50,200},也可以用%@格式说明符插入自己的对象,也可以用变量

17.5 SELF足够了

self就表示对象本身

17.6 字符串运算符

BEGINSWITH

ENDSWITH

CONTAINS

[c],[d],[cd],后缀表示不区分大小写,不区分发音符号,两这个都不区分

17.7 LIKE运算符

类似SQL的LIKES

LIKE,与通配符“*”表示任意多和“?”表示一个结合使用

LIKE也接受[cd]符号

MATCHES可以使用正则表达式

 

Car *makeCar (NSString *name, NSString *make, NSString *model,
			  int modelYear, int numberOfDoors, float mileage,
			  int horsepower) {
	Car *car = [[[Car alloc] init] autorelease];
	
	car.name = name;
	car.make = make;
	car.model = model;
	car.modelYear = modelYear;
	car.numberOfDoors = numberOfDoors;
	car.mileage = mileage;
	
	Slant6 *engine = [[[Slant6 alloc] init] autorelease];
	[engine setValue: [NSNumber numberWithInt: horsepower]
			  forKey: @"horsepower"];
	car.engine = engine;
	
	
	// Make some tires.
	// int i;
	for (int i = 0; i < 4; i++) {
		Tire * tire= [[[Tire alloc] init] autorelease];
		[car setTire: tire  atIndex: i];
	}
	
	return (car);
	
} // makeCar


int main (int argc, const char * argv[])
{
    NSAutoreleasePool *pool;
    pool = [[NSAutoreleasePool alloc] init];
	
    Garage *garage = [[Garage alloc] init];
    garage.name = @"Joe's Garage";
	
	Car *car;
	car = makeCar (@"Herbie", @"Honda", @"CRX", 1984, 2, 34000, 58);
	[garage addCar: car];

	NSPredicate *predicate;
	predicate = [NSPredicate predicateWithFormat: @"name == 'Herbie'"];
    BOOL match = [predicate evaluateWithObject: car];
    NSLog (@"%s", (match) ? "YES" : "NO");
    
    predicate = [NSPredicate predicateWithFormat: @"engine.horsepower > 150"];
    match = [predicate evaluateWithObject: car];
	NSLog (@"%s", (match) ? "YES" : "NO");
    
    predicate = [NSPredicate predicateWithFormat: @"name == %@", @"Herbie"];
    match = [predicate evaluateWithObject: car];
  	NSLog (@"%s", (match) ? "YES" : "NO");
    
    predicate = [NSPredicate predicateWithFormat: @"%K == %@", @"name", @"Herbie"];
    match = [predicate evaluateWithObject: car];
  	NSLog (@"%s", (match) ? "YES" : "NO");
    
    NSPredicate *predicateTemplate = [NSPredicate predicateWithFormat:@"name == $NAME"];
    NSDictionary *varDict;
    varDict = [NSDictionary dictionaryWithObjectsAndKeys:
               @"Herbie", @"NAME", nil];
    predicate = [predicateTemplate predicateWithSubstitutionVariables: varDict];
    NSLog(@"SNORGLE: %@", predicate);
    match = [predicate evaluateWithObject: car];
  	NSLog (@"%s", (match) ? "YES" : "NO");
    
    
	car = makeCar (@"Badger", @"Acura", @"Integra", 1987, 5, 217036.7, 130);
	[garage addCar: car];
	
	car = makeCar (@"Elvis", @"Acura", @"Legend", 1989, 4, 28123.4, 151);
	[garage addCar: car];
	
	car = makeCar (@"Phoenix", @"Pontiac", @"Firebird", 1969, 2, 85128.3, 345);
	[garage addCar: car];
	
	car = makeCar (@"Streaker", @"Pontiac", @"Silver Streak", 1950, 2, 39100.0, 36);
	[garage addCar: car];
	
	car = makeCar (@"Judge", @"Pontiac", @"GTO", 1969, 2, 45132.2, 370);
	[garage addCar: car];
	
	car = makeCar (@"Paper Car", @"Plymouth", @"Valiant", 1965, 2, 76800, 105);
	[garage addCar: car];
	
    predicate = [NSPredicate predicateWithFormat: @"engine.horsepower > 150"];
    NSArray *cars = [garage cars];
    for (Car *car in [garage cars]) {
        if ([predicate evaluateWithObject: car]) {
            NSLog (@"%@", car.name);
        }
    }

    predicate = [NSPredicate predicateWithFormat: @"engine.horsepower > 150"];
    NSArray *results;
    results = [cars filteredArrayUsingPredicate: predicate];
    NSLog (@"%@", results);
    
    NSArray *names;
    names = [results valueForKey:@"name"];
    NSLog (@"%@", names);
    
    NSMutableArray *carsCopy = [cars mutableCopy];
    [carsCopy filterUsingPredicate: predicate];
    NSLog (@"%@", carsCopy);
    
    predicate = [NSPredicate predicateWithFormat: @"engine.horsepower > %d", 50];
    results = [cars filteredArrayUsingPredicate: predicate];
    NSLog (@"%@", results);
    
    predicateTemplate = [NSPredicate predicateWithFormat: @"engine.horsepower > $POWER"];
    varDict = [NSDictionary dictionaryWithObjectsAndKeys:
               [NSNumber numberWithInt: 150], @"POWER", nil];
    predicate = [predicateTemplate predicateWithSubstitutionVariables: varDict];
    results = [cars filteredArrayUsingPredicate: predicate];
    NSLog (@"%@", results);
    
    predicate = [NSPredicate predicateWithFormat:
                 @"(engine.horsepower > 50) AND (engine.horsepower < 200)"];
    results = [cars filteredArrayUsingPredicate: predicate];
    NSLog (@"oop %@", results);
    
    predicate = [NSPredicate predicateWithFormat: @"name < 'Newton'"];
    results = [cars filteredArrayUsingPredicate: predicate];
    NSLog (@"%@", [results valueForKey: @"name"]);
    
    predicate = [NSPredicate predicateWithFormat:
                 @"engine.horsepower BETWEEN { 50, 200 }"];
    results = [cars filteredArrayUsingPredicate: predicate];
    NSLog (@"%@", results);
    
    NSArray *betweens = [NSArray arrayWithObjects:
                         [NSNumber numberWithInt: 50], [NSNumber numberWithInt: 200], nil];
    predicate = [NSPredicate predicateWithFormat: @"engine.horsepower BETWEEN %@", betweens];
    results = [cars filteredArrayUsingPredicate: predicate];
    NSLog (@"%@", results);

    predicateTemplate = [NSPredicate predicateWithFormat: @"engine.horsepower BETWEEN $POWERS"];
    varDict = [NSDictionary dictionaryWithObjectsAndKeys: betweens, @"POWERS", nil];
    predicate = [predicateTemplate predicateWithSubstitutionVariables: varDict];
    results = [cars filteredArrayUsingPredicate: predicate];
    NSLog (@"%@", results);
    
    predicate = [NSPredicate predicateWithFormat: @"name IN { 'Herbie', 'Snugs', 'Badger', 'Flap' }"];
    results = [cars filteredArrayUsingPredicate: predicate];
    NSLog (@"%@", [results valueForKey: @"name"]);

    predicate = [NSPredicate predicateWithFormat: @"SELF.name IN { 'Herbie', 'Snugs', 'Badger', 'Flap' }"];
    results = [cars filteredArrayUsingPredicate: predicate];
    NSLog (@"%@", [results valueForKey: @"name"]);
    
    names = [cars valueForKey: @"name"];
    predicate = [NSPredicate predicateWithFormat: @"SELF IN { 'Herbie', 'Snugs', 'Badger', 'Flap' }"];
    results = [names filteredArrayUsingPredicate: predicate];
    NSLog (@"%@", results);
    
    predicate = [NSPredicate predicateWithFormat: @"name BEGINSWITH 'Bad'"];
    results = [cars filteredArrayUsingPredicate: predicate];
    NSLog (@"%@", results);
    
    predicate = [NSPredicate predicateWithFormat: @"name BEGINSWITH 'HERB'"];
    results = [cars filteredArrayUsingPredicate: predicate];
    NSLog (@"%@", results);
    
    predicate = [NSPredicate predicateWithFormat: @"name BEGINSWITH[cd] 'HERB'"];
    results = [cars filteredArrayUsingPredicate: predicate];
    NSLog (@"%@", results);
    
    predicate = [NSPredicate predicateWithFormat: @"name LIKE[cd] '*er*'"];
    results = [cars filteredArrayUsingPredicate: predicate];
    NSLog (@"%@", results);
    
    predicate = [NSPredicate predicateWithFormat: @"name LIKE[cd] '???er*'"];
    results = [cars filteredArrayUsingPredicate: predicate];
    NSLog (@"%@", results);
    
    NSArray *names1 = [NSArray arrayWithObjects: @"Herbie", @"Badger", @"Judge", @"Elvis", nil];
    NSArray *names2 = [NSArray arrayWithObjects: @"Judge", @"Paper Car", @"Badger", @"Phoenix", nil];

    predicate = [NSPredicate predicateWithFormat: @"SELF IN %@", names1];
    results = [names2 filteredArrayUsingPredicate: predicate];
    NSLog (@"%@", predicate);
    NSLog (@"%@", results);
    
        
    return 0;

    
    
    predicate = [NSPredicate predicateWithFormat: @"modelYear > 1970"];
    results = [cars filteredArrayUsingPredicate: predicate];
    NSLog (@"%@", results);
	
    predicate = [NSPredicate predicateWithFormat: @"name contains[cd] 'er'"];
    results = [cars filteredArrayUsingPredicate: predicate];
    NSLog (@"%@", results);

    predicate = [NSPredicate predicateWithFormat: @"name beginswith 'B'"];
    results = [cars filteredArrayUsingPredicate: predicate];
    NSLog (@"%@", results);
	
	predicate = [NSPredicate predicateWithFormat: @"%K beginswith %@",
				 @"name", @"B"];
    results = [cars filteredArrayUsingPredicate: predicate];
    NSLog (@"with args : %@", results);
	
	predicateTemplate = [NSPredicate predicateWithFormat: @"name beginswith $NAME"];
	NSDictionary *dict = [NSDictionary 
						  dictionaryWithObjectsAndKeys: @"Bad", @"NAME", nil];
	predicate = [predicateTemplate predicateWithSubstitutionVariables:dict];
	NSLog (@"SNORGLE: %@", predicate);
	
	predicate = [NSPredicate predicateWithFormat: @"name in { 'Badger', 'Judge', 'Elvis' }"];
	results = [cars filteredArrayUsingPredicate: predicate];
    NSLog (@"%@", results);
	
	predicateTemplate = [NSPredicate predicateWithFormat: @"name in $NAME_LIST"];
	names = [NSArray arrayWithObjects:@"Badger", @"Judge", @"Elvis", nil];
	dict = [NSDictionary 
						  dictionaryWithObjectsAndKeys: names, @"NAME_LIST", nil];
	predicate = [predicateTemplate predicateWithSubstitutionVariables:dict];
	results = [cars filteredArrayUsingPredicate: predicate];
    NSLog (@"%@", results);
	
	predicateTemplate = [NSPredicate predicateWithFormat: @"%K in $NAME_LIST", @"name"];
	dict = [NSDictionary 
	dictionaryWithObjectsAndKeys: names, @"NAME_LIST", nil];
	predicate = [predicateTemplate predicateWithSubstitutionVariables:dict];
	results = [cars filteredArrayUsingPredicate: predicate];
    NSLog (@"%@", results);
	NSLog (@"xSNORGLE: %@", predicate);
	
	// SELF is optional here.
	predicate = [NSPredicate predicateWithFormat:@"SELF.name in { 'Badger', 'Judge', 'Elvis' }"];
	
	for (Car *car in cars) {
		if ([predicate evaluateWithObject: car]) {
			NSLog (@"SNORK : %@ matches", car.name);
		}
	}
	
	
#if 0
	predicate = [NSPredicate predicateWithFormat: @"ANY engine.horsepower > 200"];
    results = [cars filteredArrayUsingPredicate: predicate];
	NSLog (@"SNORGLE: %@", predicate);
#endif
	
    predicate = [NSPredicate predicateWithFormat: @"engine.horsepower > 200"];
    results = [cars filteredArrayUsingPredicate: predicate];
    NSLog (@"%@", results);
	
    predicate = [NSPredicate predicateWithFormat: @"tires.@sum.pressure > 10"];
    results = [cars filteredArrayUsingPredicate: predicate];
    NSLog (@"%@", results);

#if 0
	predicate = [NSPredicate predicateWithFormat: @"ALL engine.horsepower > 30"];
	results = [cars filteredArrayUsingPredicate: predicate];
	NSLog (@"%@", results);
#endif
	
	
    [garage release];
    
    [pool release];
    
    return (0);
    
} // main

 

判断字符串首字母是否为字母。 
Objective-c代码 
NSString *regex = @"[A-Za-z]+"; 
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex]; 
if ([predicate evaluateWithObject:aString]) { 

 

 

 

 

 

 

分享到:
评论

相关推荐

    [Objective-c程序设计].杨正洪等.扫描版

    《Objective-C程序设计》(作者杨正洪、郑齐心、李建国)通过大量的实例系统地介绍了Objective-C语言的基本概念、语法规则、框架、类库及开发环境。读者在阅读本书后,可以掌握Objective-C语言的基本内容,并进行...

    Objective-C的语法与Cocoa框架

    3. Objective-C中的布尔类型 4. Objective-C中的null 5. 与C混合编写 6. 对象的初始化 7. Objective-C的description方法 8. Objective-C的异常处理 9. id类型 10. 类的继承 11. 动态判定与选择器 12. 类别Category ...

    Learn Objective-C on the Mac

    Learn Objective-C on the Mac: For OS X and iOS, Second Edition updates a best selling book and is an extensive, newly updated guide to Objective-C. Objective-C is a powerful, object-oriented ...

    iOS App开发中Objective-C使用正则表达式进行匹配的方法

    iOS中有三种方式来实现正则表达式的匹配。现在将他们都记录在这里: ...NSPredicate *predicate = [NSPredicate predicateWithFormat:@SELF MATCHES %@, regex]; BOOL isValid = [predicate evaluat

    ios-cloudkit-snippets:使用 CloudKit 框架的示例代码

    如何使用 Objective-C 使用 NSPredicate 从容器的公共数据库中查询记录 如何使用 Swift 使用 NSPredicate 从容器的公共数据库中查询记录 ####设置您的项目 在 Xcode 中,只需打开iCloud 功能,检查 CloudKit,然后...

    GraffitiSamples:Graffiti是用于创建无代码本机应用程序的新轻量级框架

    但是它仍然是常规的本机应用程序,所有这些对象都可以在运行时访问,因此您也可以在swift / objective-c代码中使用它们。 无论如何,您的代码库将非常小。 例如,考虑以下视图控制器: 当然,它具有您需要的所有...

    Core.Data.in.Swift.Data.Storage.and.Management.for.iOS.and.OSX

    This book is based on Core Data in Objective-C, Third Edition. It focuses on Swift and adds an additional chapter on how to integrate Core Data with an efficient network implementation, with best ...

    NSCollectionAddition:为 NSCollection 类添加一些方便的函数方法

    NSCollectionAddition 通过使用预处理器 / obj-c 块语法为 NSCollection 类添加了方便的/函数式方法(大多数是从 Scala 的集合中窃取的),使开发更容易。 例如, [NSArray arrayWithObjects: @"First", @"Second...

    RealmSubqueryHelper:RLMObject 类别以简化执行包含对链接对象的子查询的查询

    这个类别将NSPredicate 、 SUBQUERY隐藏的宝石SUBQUERY了 Realm 中。 例如,给定这个 Realm 设置: Person : RLMObject@property NSString *Id;@property RLMArray&lt;Dog&gt; *dogs;Dog : RLMObject@property BOOL ...

    applebugs:我提交的雷达示例代码集

    苹果虫 我提交的雷达代码示例集合。 UTF8PredicateBug NSPredicate 不支持 UTF8 键路径 执照 麻省理工学院许可。

    TLFormView:通用的iOS表单

    它也有一些不错的功能,如:使用条件可见NSPredicate ,就地帮助每个字段UIPopoverControler和即时编辑/只读模式切换等等。 有一系列博客文章,名为: TLFormView: 的未来第一和的形式。快速范例 // Declare your ...

    DXFileManager:一个文件管理器包装 NSFileManager

    DX文件管理器 一个文件管理器包装 NSFileManager,基于构建。 有些不同: 不使用默认文档路径,也不每次都循环所有路径来搜索正确的路径。... 使用 NSPredicate 过滤结果搜索路径。 查看演示以获取更多详细信息

Global site tag (gtag.js) - Google Analytics