`
啸笑天
  • 浏览: 3462252 次
  • 性别: 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基础教程源代码 Learn objective-C on the Mac Mark Dalrymple著书

    1. **Objective-C语法**:Objective-C的语法基于C语言,但引入了类、接口和消息传递等概念。这包括定义类、属性(@property)和方法(@selector)的语法,以及理解类接口(.h)和实现(.m)文件的作用。 2. **对象...

    这是一个基于Objective-C语言的基础案例集。旨在用于给初学者快速了解Objective-C语言的语法。.zip

    1. **Objective-C的起源与特性**:Objective-C是在C语言的基础上扩展的,增加了消息传递机制和面向对象特性。它的语法包含C语言的所有部分,同时引入了类、继承、多态等OOP概念。 2. **类与对象**:在Objective-C中...

    《Objective-C基础教程(第二版)》英文版

    Objective-C作为C语言的超集,在OS X和iOS系统的应用开发中扮演着核心角色。本书不仅介绍了Objective-C的基本语法,还向读者展示了如何结合使用苹果的Cocoa框架(OS X)和Cocoa Touch框架(iOS)。 首先,了解...

    0基础iOS开发学习计划Objective-c语言内容概述.doc

    Objective-C是一种结合了C语言特性和面向对象编程思想的语言,它是苹果iOS和macOS应用开发的基础语言之一。Objective-C诞生于20世纪80年代,由Brace N. Koch等人设计并发展起来。随着iOS和macOS系统的流行,...

    Objective-C基础教程随书源码 Learn Objective-C Samples

    1. **面向对象编程(Object-Oriented Programming, OOP)**:Objective-C基于C语言,并在其基础上引入了面向对象的概念,如类、对象、继承、封装和多态等。学习Objective-C首先要理解这些OOP的基本概念。 2. **类...

    Learn Objective-c on the Mac 2nd edition

    《Learn Objective-C on the Mac 第二版》是一本基础教程书籍,主要面向初学者介绍Objective-C语言。Objective-C是C语言的超集,广泛应用于开发具有真正OS X或iOS风格的应用程序。本书不仅涵盖Objective-C的基础知识...

    Learn Objective-C on the Mac

    《在Mac上学习Objective-C》是一本面向开发者介绍如何使用Objective-C语言为Mac OS X和iOS平台开发应用程序的书籍。Objective-C是苹果公司用来开发iOS和OS X应用程序的原生编程语言,它基于C语言并加入了面向对象的...

    Apress Learn Objective-C on the Mac 2nd Edition.pdf

    Objective-C是一种广泛用于开发苹果公司OS X和iOS平台应用程序的语言,它是C语言的一个超集。本书旨在教授读者Objective-C的基本语法和概念,并介绍了与之配套的苹果公司的Cocoa框架(OS X)和Cocoa Touch框架(iOS...

    一些学习Objective-C编程语言的资源.zip

    1. **Objective-C基础**:Objective-C是C语言的超集,这意味着你可以直接在Objective-C中编写C代码。它引入了Smalltalk的“消息传递”机制,使得对象间的通信更加灵活。了解类、对象、方法、继承、多态和封装这些...

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

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

    objective-c 教程

    Objective-C 是苹果公司为其操作系统(包括macOS和iOS)开发的一种面向对象的编程语言,它在C语言的基础上扩展了Smalltalk的特性。本教程旨在为初学者提供一个基础且易于理解的Objective-C学习路径,帮助你快速入门...

    Objective-C基础教程

    Objective-C的起源可以追溯到C语言,因此它保留了C的语法结构,同时引入了面向对象的特性。它的主要特点包括消息传递、类、协议和动态类型等。让我们逐一解析这些关键概念: 1. **消息传递**: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 ...

    Objective-C基础教程 第2版

    Objective-C是在C语言的基础上扩展的,它引入了消息传递机制,使得对象间的通信更为灵活。在Objective-C中,一切皆为对象,这得益于它的面向对象特性。"Object"标签指出了本教程的重点,即对象和类的概念。 1. **...

    IOS学生信息系统Objective-C实现

    首先,Objective-C作为苹果生态系统的主要开发语言,其语法特性深受C语言和Smalltalk的影响,支持动态类型和消息传递机制,为开发者提供了高度的灵活性。在本项目中,Objective-C用于构建整个应用的架构,包括视图...

    NSHIPSTER:Obscure Topics In Cocoa & Objective-C

    - Objective-C类型系统中的nil和NULL:不同编程语言或框架对空值的表示各不相同,在Objective-C中,nil通常用于对象,而NULL用于C语言中的指针。 - BOOL类型:在Objective-C中,BOOL类型表示布尔值,并且与基本的...

    上半部 Objective-C2.0程序设计(原书第2版)

    1. **Objective-C概述**:Objective-C是C语言的超集,它引入了Smalltalk的面向对象特性。书中会讲解Objective-C的历史、语法特点以及与其他语言的区别。 2. **基础语法**:包括变量声明、常量、数据类型、运算符、...

    objective-2.0课件及书上的例子代码

    1. **Objective-C语言基础**:Objective-C是C语言的超集,它在C的基础上增加了Smalltalk式的面向对象特性。学习Objective-C,你需要理解类、对象、消息传递等概念,以及如何定义接口(@interface)和实现(@...

    objective-c中正则表达式

    总的来说,Objective-C中的正则表达式结合NSRegularExpression和NSPredicate,为我们提供了强大的文本验证功能,能够有效地确保用户输入的数据符合预期的格式,从而提高应用的用户体验和数据安全性。在实际开发中,...

Global site tag (gtag.js) - Google Analytics