Quantcast
Channel: CSDN博客移动开发推荐文章
Viewing all articles
Browse latest Browse all 5930

谓词技术的使用 NSPredicate

$
0
0

前言

在进行一些数据的筛选的时候经常使用到它。

例如: CoreData的数据查询、按照特定条件(日期)排序的数据、从数组进行数据查询等等。

正文

谓词技术的使用 NSPredicate (以一定的条件(特定日期)过滤maTemp数组,即进行大数据搜索。)

示例一,将含有日期属性的对象数组中,进行按照日期重新进行分组

使用谓词进行数据分组 (数组元素为 自定义类型)

//2.按照日期进行分组展示

//     重新按照日期进行分组组织数据

//     找出不重复的日期

    /**
  对象操作:
     针对数组的情况
     @distinctUnionOfObjects:返回指定属性去重后的值的数组

     @unionOfObjects:返回指定属性的值的数组,不去重

     属性的值不能为空,否则产生异常。


*/

    //1)取出日期分组

    NSArray *arDistinct = [maTemp valueForKeyPath:@"@distinctUnionOfObjects.strDateCreated"];//maTemp是一些含有日期属性的对象集合

    //2)构建排序规则NSComparator

    NSComparator cmptr = ^(id obj1, id obj2){

        NSString *strData1 = obj1;

        NSString *strData2 = obj2;



        NSComparisonResult ret = [strData1 compare:strData2];

        return ret;

//        if (ret == NSOrderedAscending)

//       

//        if (aEcouponData1.nAmount > aEcouponData2.nAmount) {

//            return (NSComparisonResult)NSOrderedDescending;

//        }

//       

//        if (aEcouponData1.nAmount < aEcouponData2.nAmount) {

//            return (NSComparisonResult)NSOrderedAscending;

//        }

//        return (NSComparisonResult)NSOrderedSame;

    };




//     3)按数字从小到大进行排序(将最新的数据显示在前面)

    NSArray  *arSorted = [arDistinct sortedArrayUsingComparator:cmptr];
    arSorted = arSorted.reverseObjectEnumerator.allObjects;//顺序取反

    NSPredicate *predicate = nil;

//     4)按照日期进行分组

    for (NSString *strDateCreated in arSorted)
    {

        predicate = [NSPredicate predicateWithFormat:@"strDateCreated == %@", strDateCreated];

        NSArray *arFiltered = [maTemp filteredArrayUsingPredicate:predicate];//以一定的条件(特定日期)过滤maTemp数组,即进行大数据搜索。      

        OrderQueryGroupData *data = [OrderQueryGroupData alloc];
        data.strDateCreated = strDateCreated;
        data.maOrderData = [NSMutableArray arrayWithArray:arFiltered];
        data.maOrderDataF = [IPOrderDataFrame frameListWith:data.maOrderData];
        [self.maOrderQuery addObject:data];

    }

示例代码二: 数据的过滤,城市搜索

城市搜索

  */

    //方式二: 谓词技术的使用

    searchText  = searchText.uppercaseString;

    NSPredicate *predicate = [NSPredicate predicateWithFormat:@" pinYinHead.uppercaseString  contains %@ or  name.uppercaseString  contains %@  or pinYin.uppercaseString  contains %@ ",searchText,searchText,searchText];

    return [_cityModels filteredArrayUsingPredicate:predicate];



}



//方式一。
+ (NSArray *)searchcityModelsWithSeatchText:(NSString *)searchText{



    NSMutableArray *array = [NSMutableArray array];

    searchText = [searchText uppercaseString];

    for (DKCityModel *obj in _cityModels) {

        if ([obj.name.uppercaseString containsString:searchText] || [obj.pinYin.uppercaseString containsString:searchText] || [obj.pinYinHead.uppercaseString containsString:searchText]) {

            [array addObject:obj];

        }

    }

    return array;

}

示例代码3:银行列表的过滤

多个过滤条件的拼接

#pragma mark - ********     //列表的银行过滤
- (void)predicateBankList{
    if ([Session Instance].arrOnlySupportBankList.count == 0) {
        return;
    }

    NSMutableString *stringpredicate = [NSMutableString string] ;
//    for (NSString *code in ) {
//        if ([code isEqualToString:[Session Instance].arrOnlySupportBankList[0]]) {
//            [stringpredicate appendFormat:@"  strBankNO ==  %@ ",code];
//        }else {
//            [stringpredicate appendFormat:@"  strBankNO ==  %@ ",code];
//        }
//    }
    NSInteger count = [Session Instance].arrOnlySupportBankList.count;
    for (int i = 0;  i<count;i++) {

        if (count == 1) {
            [stringpredicate appendFormat:@"  strBankNO ==  '%@' ",[Session Instance].arrOnlySupportBankList[i]];
        }else if (count>1){

            if (i == 0) {
                [stringpredicate appendFormat:@"  strBankNO ==  '%@' ",[Session Instance].arrOnlySupportBankList[i]];
            }else{
                [stringpredicate appendFormat:@"or  strBankNO ==  '%@' ",[Session Instance].arrOnlySupportBankList[i]];
            }
        }

    }
    if ([stringpredicate isEqualToString:@"" ] ) {
        return;
    }

    NSPredicate *predicate = [NSPredicate predicateWithFormat:stringpredicate];
    self.bankListDepositCard = [NSMutableArray arrayWithArray:[ self.bankListDepositCard  filteredArrayUsingPredicate:predicate]];
    self.bankListCreditCard = [NSMutableArray arrayWithArray:[ self.bankListCreditCard  filteredArrayUsingPredicate:predicate]];

}

示例4: 字符串数组的过滤(数组元素为系统的自有类型)

字符串数组的过滤

/**

 BankInfoData 对象的 的银行卡编号是否包含在 arrOnlySupportBankList 银行卡编号数组中
 @return bool
 */
- (BOOL)isaBankSelectedEqualToBusinessBank:(KNData*)data{



   NSArray *arrOnlySupportBankList=  [KNSession Instance].arrOnlySupportBankList;//kevin
    NSArray *tmp = [NSArray array];
    NSString *stringpredicate = [NSString stringWithFormat:@" self ==  '%@'",data.strBankNO];
    NSPredicate *predicate = [NSPredicate predicateWithFormat:stringpredicate];
    tmp = [NSMutableArray arrayWithArray:[  arrOnlySupportBankList filteredArrayUsingPredicate:predicate]];
    if (tmp.count>0) {
        return YES;
    }else{
        return NO;
    }
}

例子5: Core Data的数据查询

例子:保存未读消息

#pragma mark - 保存未读消息
/** 先查询,在修改 */
+ (void)saveMessageWithMessage:(IPMessageDetailData*)data{
    if (data.messageId == nil || data == nil){
        return;
    }

    NSManagedObjectContext *context = [IPMessageDataTool shareContext];
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    request.entity = [NSEntityDescription entityForName:@"KNMessage" inManagedObjectContext:context];
    // 设置排序(按照messageId降序)
    NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"messageId" ascending:NO];
    request.sortDescriptors = [NSArray arrayWithObject:sort];
    // 设置条件过滤(搜索name中包含字符串"Itcast-1"的记录,注意:设置条件过滤时,数据库SQL语句中的%要用*来代替,所以%Itcast-1%应该写成*Itcast-1*)
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"messageId = %@  AND operateID = %@",data.messageId,[SessionMgr Instance].operateID];
    request.predicate = predicate;
    // 执行请求
    //    request.fetchLimit = 50;
    NSError *error = nil;
    NSArray *objs = [context executeFetchRequest:request error:&error];
    if (error) {
        [NSException raise:@"查询错误" format:@"%@", [error localizedDescription]];
    }
    Message *tmpMessage;
    if (objs.count>0) {
        tmpMessage = objs[0];
        return;
    }else{
        tmpMessage = [NSEntityDescription insertNewObjectForEntityForName:@"Message" inManagedObjectContext:context];
    }
    tmpMessage.messageExpiredTime = data.messageExpiredTime;
    tmpMessage.messageIssueTime = data.messageIssueTime;
    tmpMessage.messageId = data.messageId;
    tmpMessage.messageTitle = data.messageTitle;
    tmpMessage.operateID = [SessionMgr Instance].operateID;
    tmpMessage.isRead = NO;
    BOOL success = [context save:&error];
    if (!success) {
        [NSException raise:@"访问数据库错误" format:@"%@", [error localizedDescription]];
    }
}
作者:u011018979 发表于2017/7/1 15:39:33 原文链接
阅读:200 评论:0 查看评论

Viewing all articles
Browse latest Browse all 5930

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>