简体   繁体   中英

IOS/Objective-C: Out of Range Error with NSPredicate

I have built an NSPredicate similar to that below before and it worked perfectly. However, this time, it is generating the error:

'NSRangeException', reason: '-[NSTaggedPointerString characterAtIndex:]: Index 1 out of bounds; string length 1'

Here is how I build the predicate:

 NSString *shortTitleClause = nil;
    NSString *longTitleClause = nil;

Edit:

Adding clauses:

shortTitleClause =[NSString stringWithFormat:@"(shorttitle contains[c] %@)", searchText];
 longTitleClause =[NSString stringWithFormat:@"(longtitle contains[c] %@)", searchText];

//My actual predicate has many more clauses but am getting same error no matter how many.

NSMutableArray *predArr = [@[] mutableCopy]; 

    if (shortTitleClause.length > 0){
        [predArr addObject:shortTitleClause];
    }
    if (longTitleClause.length > 0){
        [predArr addObject:longTitleClause];
    }
NSString *predStr = [predArr componentsJoinedByString:@"||"];
   NSPredicate *resultPredicate = [NSPredicate predicateWithFormat:predStr];
   searchResults = [theBooks filteredArrayUsingPredicate:resultPredicate];

When searching for the letter 'S' the predicate logs as: `(shorttitle contains[c] S)||(longtitle contains[c] S)`

It is not clear to me what the taggedPointerString refers to me. Can anyone see why I am getting this error?

You cannot use stringWithFormat to replace %@ values when preparing predicates. Use predicateWithFormat instead. And don't join them using componentsJoinedByString - use NSCompoundPredicate to combine multiple predicates:

shortTitlePredicate = [NSPredicate predicateWithFormat:@"(shorttitle contains[c] %@)", searchText];
longTitlePredicate = [NSPredicate predicateWithFormat:@"(longtitle contains[c] %@)", searchText];

NSPredicate *resultPredicate = [NSCompoundPredicate orPredicateWithSubpredicates:@[shortTitlePredicate,longTitlePredicate]];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM