开发者

Core Data Query Multiple Columns with Single Search String

I have a simple Core Data model with two string attributes (size and category)开发者_如何学运维. Given a search string like 'small widget' is it possible to return records that match all the query words to at least one attribute (i.e. all records with 'small' size and 'widget' category)? I currently have:

NSString *search = @"small widget"
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"size contains[cd] %@ OR category contains[cd] %@", search, search];
...

This won't return any results (as no category or size equals "small widget"). Any suggestions? Note that the search strings will be user entered from a text field and may come in any order so I can't split up manually.


I haven't tested it but it looks like your want this:

NSString *search = @"small widget";
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"%@ contains[cd] size AND %@ contains[cd] category", search, search];

The search string would contain (or not) the size and the category, you should ask if the current size or category is contained on the search string.

You could also split the search string and modify your predicate. You should them to identify the one that performs better

NSString *search = @"small widget";
    NSArray *array = [search componentsSeparatedByString:@" "];
    NSMutableArray *subPredicates = [NSMutableArray array];
    for (NSString *q in array) {
        [subPredicates addObject:
         [NSPredicate predicateWithFormat:@"size contains[cd] %@ OR category contains[cd] %@", q, q]];
    }
    NSCompoundPredicate *predicate = [[[NSCompoundPredicate alloc] initWithType:NSAndPredicateType
                                                                 subpredicates:subPredicates] autorelease];


For Swift you can fetch multiple columns by using propertiesToFetch

let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "<YOUR ENTITY NAME>")
let predicate = NSPredicate(format: "<YOUR PREDICATE>")
fetchRequest.predicate = predicate
fetchRequest.resultType = .dictionaryResultType


// Here is where you can query multiple columns, you can add as much columns as you want and fetch them as an array of dictionaries
fetchRequest.propertiesToFetch = ["column1", "column2", "column3, "column4"]


let sort = NSSortDescriptor(key: "column1", ascending: false)
fetchRequest.sortDescriptors = [sort]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜