开发者

Core Data Query, NSPredicate

I have an entity called "Sessions" and it contains an NSDate attr开发者_如何学运维ibute.

What I want is to be able to query the core data model and get an array of the DAYS of the NSDates, without any duplicates.

For example, if I have 5 sessions on thursday, 2 on friday and 1 on sunday, I want an array of "Thursday", "Friday", "Sunday".

(It doesn't necessarily have to have that string format, that part I can figure out and modify myself.)

What would be the proper way to approach this method?


You cannot. This is not what NSPredicate is for. You'll have to fetch the Session objects, and for each one, figure out what day it's on. It'll be something like this:

NSArray *sessions = ...; // an array of Session objects
NSMutableSet *days = [NSMutableSet set];
NSDateFormatter *f = [[NSDateFormatter alloc] init];
[f setDateFormat:@"EEEE"]; // this is the name of the day of the week, spelled out
for (Session *session in sessions) {
  NSDate *d = [session date];
  NSString *dayOfWeek = [f stringFromDate:d];
  [days addObject:dayOfWeek];
}
[f release];
NSLog(@"days: %@", days);

Note that since we're using an NSSet, the days of the week will be unordered.


I do not think you can get what you want as the result of a query. You could use -[NSFetchRequest setReturnsDistinctObject:] to return only results with unique NSDate values, but since you are only concerned with the day of the week, you may be out of luck.

However, you could store the day of the week in your entity as an integer and then search for that.

You could also fetch all Sessions entities, and then build a dictionary of the days of the week from there (where results array is an array containing all of your fetched sessions):

// This date formatter will return a string with the full weekday, i.e. "Monday"
NSDateFormatter *dfText = [[NSDateFormatter alloc] init];
[df setDateFormat:@"EEEE"];

// This date formatter will return a string with the number of the weekday, i.e. "1"
NSDateFormatter *dfNumber = [[NSDateFormatter alloc] init];
[df setDateFormat:@"c"];

NSMutableDictionary *weekdays = [NSMutableDictionary dictionary];

for (Session *curSession in resultsArray) {

    NSString *weekdayNumber = [dfNumber stringFromDate:curSession.Date];

    if (![weekdays objectForKey:weekdayNumber]) {
        [weekdays setObject:[dfText stringFromDate:curSession.Date] forKey:weekdayNumber];
    }

}

[dfText release];
[dfNumber release];
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜