谓词与通知

来源:互联网 发布:java连接mysql的jar包 编辑:程序博客网 时间:2024/06/18 04:48
谓词的基本概念






概念
cocoa中提供了NSPredicate类,指定过滤器的条件。将符合条件的对象保留下来。


创建谓词


// 设置谓词条件
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"age <= 28"];
for (Person *person in array) {
// 表示指定的对象是否满足谓词条件
if ([predicate evaluateWithObject:person]) {
      //NSLog(@"person name : %@", person.name);
}c vd
}
// 返回一个符合谓词条件的数组
NSArray *newArray = [array filteredArrayUsingPredicate:predicate];
for (Person *person in newArray) {
    //NSLog(@"person name : %@", [person valueForKey:@"_name"]);
}






格式占位符


// 格式占位符号
NSPredicate *pre = [NSPredicate predicateWithFormat:@" age <= %d", 30];
NSArray *array2 = [array filteredArrayUsingPredicate:pre];
for (Person *person in array2) {
//NSLog(@"person name 2 %@", [person valueForKey:@"_name"]);
}




运算符


逻辑运算符
// 运算符号 的加入 谓词不区分大小 && AND || OR
NSPredicate *pre3 = [NSPredicate predicateWithFormat:@"name > 'bruse' &&
age < %d", 30];
NSArray *array4 = [array filteredArrayUsingPredicate:pre3];






IN
// 关键字 注意字符串一定要添加''
NSPredicate *pre4 = [NSPredicate predicateWithFormat:@"self.name IN
{'rose', 'bruse'}"];
NSArray *array5 = [array filteredArrayUsingPredicate:pre4];
NSLog(@"person name : %@", [array5 valueForKey:@"_name"]);






关键字


以**开始——BEGINSWITH
// BEGINSWITH 检查某个字是否以**开头
NSPredicate *pre5 = [NSPredicate predicateWithFormat:@"self.name
BEGINSWITH 'J'"];
NSArray *array6 = [array filteredArrayUsingPredicate:pre5];
NSLog(@"person name : %@", [array6 valueForKey:@"name"]);


以**结束——ENDSWITH
// ENDSWITH 检查某个字符是以**结尾
NSPredicate *pre6 = [NSPredicate predicateWithFormat:@"self.name endswith'e'"];
NSArray *array7 = [array filteredArrayUsingPredicate:pre6];
NSLog(@"array7 : %@", [array7 valueForKey:@"name"]);




包含——CONTAINS
// CONTAINS 检查包含某个字符
NSPredicate *pre8 = [NSPredicate predicateWithFormat:@"self.name CONTAINS'小'"];
NSArray *array8 = [array filteredArrayUsingPredicate:pre8];
NSLog(@"array8 : %@", [array8 valueForKey:@"name"]);


模糊查询——Like
// Like 检查包含某个字符
NSString *s = [NSString stringWithFormat:@"name like '*%@*'",@"a"];
NSPredicate *predicate = [NSPredicate predicateWithFormat:s];
NSLog(@"array8 : %@", [array8 valueForKey:@"name"]);








示例:


打开xcode 


点击  create  a  new  xcode  project


点击  左侧  Application  选择右侧中的 Command Line  Tool(相当于windows下的command)


         ---  next


  product Name:predicateDemo
  
  Company identifier:com.imti


  type: foundation  是一个framework




  取消选择 use Automatic  Reference  Counting




        ---  next




        ---  create




new  file...    


           name:Person
           subclass:  NSObject




Person.h


#import <Foundation/Foundation.h>


@interface Person : NSObject


@property(nonatomic,copy)NSString *name;
@property(nonatomic,retain)NSNumber *age;


@end




Person.m


加入




- (NSString *)description {
    NSString *s = [NSString stringWithFormat:@"name=%@,age=%@",_name,_age];
    return s;
}








main.m  加入


#import "Person.h"




加入




 @autoreleasepool {
        
        NSMutableArray *array = [NSMutableArray array];
        for (int i=0; i<10; i++) {
            Person *person = [[Person alloc] init];
            if (i<5) {
                person.name = [NSString stringWithFormat:@"jack-%d",i];
            } else {
                person.name = [NSString stringWithFormat:@"tom-%d",i];
            }
            person.age = @(20+i);
            [array addObject:person];
            [person release];
        }




 }






加入


        //判断是否满足条件
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"age < 25"];        




        for (Person *p in array) {
            BOOL ret = [predicate evaluateWithObject:p];
            if(ret) {
                NSLog(@"%@",p);
            }
        }






   运行




   加入 


        //对数组过滤
        NSArray *filterArray = [array filteredArrayUsingPredicate:predicate];
        NSLog(@"%@",filterArray);


   运行






现在年龄是 age < 25     25 固定好了希望动态传值




   将  NSPredicate *predicate = [NSPredicate predicateWithFormat:@"age < 25"];  


   改为    
  NSPredicate *predicate = [NSPredicate predicateWithFormat:@"age < %d", 22]; 






运行




  将      NSPredicate *predicate = [NSPredicate predicateWithFormat:@"age < %d, 22"];   


  改为       NSPredicate *predicate = [NSPredicate predicateWithFormat:@"age>25 and age<27"];   




运行


     改为      NSPredicate *predicate = [NSPredicate predicateWithFormat:@"age<25 || age>27"];  






运行


     改为      NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name='tom-8'"];  
      


运行


    改为    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name in {'tom-8','jack-3','xxx'}"];




运行


   改为  


               NSArray *inArray = @[@"tom-8",@"jack-3",@"xxx"];
               NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name in %@",inArray];        




运行


  将以上2句话注释掉 在其下加入


   
        //2.BEGINSWITH ENDSWITH  CONTAINS关键字
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name BEGINSWITH 't' || name BEGINSWITH 'j'"];
       




运行
      注释掉  NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name BEGINSWITH 't' || name BEGINSWITH 'j'"];


      加入    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name ENDSWITH '-5'"];




运行 
        
      注释掉   NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name ENDSWITH '-5'"];




      加入   NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name CONTAINS 'a'"];




运行


      注释掉  NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name CONTAINS 'a'"];


      加入    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name like '*j*'"];


运行
  
     改为    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name like '*4'"];




运行


     改为




    NSString *s = [NSString stringWithFormat:@"name like '*%@*'",@"a"];
    NSPredicate *predicate = [NSPredicate predicateWithFormat:s];


运行


     将以上2句话注释掉 在其下加入


    加入           NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name like '??c*'"];
    




运行










通知   类之间传递消息








示例:   看小孩


打开xcode 


点击  create  a  new  xcode  project


点击  左侧  Application  选择右侧中的 Command Line  Tool(相当于windows下的command)


         ---  next


  product Name:Child
  
  Company identifier:com.imti


  type: foundation  是一个framework




  取消选择 use Automatic  Reference  Counting




        ---  next




        ---  create




new  file...    


           name:Child
           subclass:  NSObject






    Child.h


#import <Foundation/Foundation.h>


#define CHILD_WEAK_NOTIFICATION @"child_weak"


@interface Child : NSObject


@property(nonatomic,assign)NSInteger sleep;


@end






   Child.m




加入




- (id)init {
    self = [super init];
    if (self != nil) {
        _sleep = 100;
        
        [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerAction:) userInfo:nil repeats:YES];
    }
    
    return self;
}


- (void)timerAction:(NSTimer *)timer {
    _sleep -= 2;
    
    NSLog(@"%ld",_sleep);
    if (_sleep < 90) {
        NSNumber *sleepNum = [NSNumber numberWithInteger:_sleep];
        NSDictionary *dic = @{@"sleep":sleepNum};
        
        //发送通知  如铃铛响动    postNotificationName通知名  object与userInfo 表示通知发送后传递出去的参数
        //发送通知后要有通知的监听者
        [[NSNotificationCenter defaultCenter]
         postNotificationName:CHILD_WEAK_NOTIFICATION
         object:[NSNumber numberWithInteger:_sleep] userInfo:dic];//传递2个参数
        [timer invalidate];
    }
}








new  file...    


           name: Father
           subclass:  NSObject




 Father.m


 加入


 #import "Child.h"




 在加入




 - (id)init {
    self = [super init];
    if (self != nil) {//通知监听者
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(weekNotification:) name:CHILD_WEAK_NOTIFICATION object:nil];
    }
    return self;
}


- (void)dealloc {
//    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:CHILD_WEAK_NOTIFICATION object:nil];
    [super dealloc];
}


- (void)weekNotification:(NSNotification *)notification {//接收通知发送过来的参数
    NSNumber *num = notification.object;
    NSDictionary *dic = notification.userInfo;
    NSLog(@"抱起小孩哄哄,_sleep=%@",dic);
}






打开 main.m


加入


#import "Child.h"
#import "Father.h"




在加入




@autoreleasepool {
        
        Father *father = [[Father alloc] init];
        Child *child = [[Child alloc] init];
        
        [[NSRunLoop currentRunLoop] run];
    }




运行


 
优先使用delege 1对1  一个类代理类只能有一个  如果通知多了程序就会跳来跳去,程序可读性不是很好
如果一个类通知有多个类监听 如 奶奶监听 妈妈监听 即1对多  一旦发送一个通知将不知道有哪些类在监听   只能在项目中搜索 CHILD_WEAK_NOTIFICATION 代码
 






今日习题
1. 熟练掌握谓词的基本用法
2. 将保姆与孩子的例子修改成键值观察模式
3. 将保姆与孩子的例子修改成通知实现
0 0
原创粉丝点击