kylef-archive / KFData

Core Data done right for iOS 5+/OS X 10.7+
http://cocoadocs.org/docsets/KFData/
BSD 2-Clause "Simplified" License
53 stars 7 forks source link

Create a nice way to generate predicates and sort descriptors #29

Closed kylef closed 11 years ago

kylef commented 11 years ago

I really hate creating sort descriptors and predicates because you often have to write the same thing. You can also hit issues later because of use with strings.

Entity

Implement either a category or on the entity class. Perhaps we can have some tool to generate these. I see http://rentzsch.github.io/mogenerator/ https://github.com/rentzsch/mogenerator/ being used a lot.

@implementation Person

+ (KFAttribute *)name {
    return [KFAttribute attributeForKey:@"name"];
}

+ (KFAttribute *)age {
    return [KFAttribute attributeForKey:@"age"];
}

@end

Equals

NSPredicate *predicate = [[Person name] equals:@"Kyle Fuller"];

Sort descriptors

NSSortDescriptor *sortDescriptor = [[Person name] ascending];
NSSortDescriptor *sortDescriptor = [[Person name] descending];

Number based comparisons

NSSortDescriptor *sortDescriptor = [[Person age] greaterThanOrEquals:@15];

I've created this as an issue for discussion, what do you think?

/cc @calvincestari @iamandybarnard

calvincestari commented 11 years ago

I really like this. I'll check out mogenerator. If we can find a clean way to do it, it'll work a treat!

nnd commented 11 years ago

This is a great idea.

In addition, exposing the attribute methods will help when creating predicates with multiple conditions. For example:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"%@ == @'Andy' AND %@ >= 10", [Person name], [Person age]];
kylef commented 11 years ago

There is also NSCompoundPredicate

[NSCompoundPredicate andPredicateWithSubpredicates:@[
    [[Person name] equals:@"Andy"],
    [[Person age] greaterThanOrEquals:@15],
]];

We could also have a wrapper around some things in NSCompoundPredicate.

@interface NSPredicate (KFData)

- (NSCompoundPredicate *)not;
- (NSCompoundPredicate *)and:(NSPredicate *);
- (NSCompoundPredicate *)or:(NSPredicate *);

@end