SKSite * site = [SKSite stackAppsSite];
//begin building our request for all questions
SKFetchRequest * request = [[SKFetchRequest alloc] init];
[request setEntity:[SKQuestion class]];
//this will hold how the favorited counts for a user
NSCountedSet * counts = [NSCountedSet set];
NSUInteger count = NSUIntegerMax;
//retrieve all the questions
for (NSUInteger offset = 0; offset < count; offset += 100) {
//starting from the appropriate offset (page)
[request setFetchOffset:offset];
NSError * error = nil;
NSArray * matches = [site executeSynchronousFetchRequest:request error:&error];
//loop through all the questions and record how many times they've been favorited
for (SKQuestion * question in matches) {
NSUInteger count = [[question favoriteCount] unsignedIntegerValue];
for (int i = 0; i < count; ++i) { [counts addObject:[question ownerID]]; }
}
if (count == NSUIntegerMax) {
count = [[request fetchTotal] unsignedIntegerValue];
}
}
[request release];
//turn the counted set into a dictionary (so we can sort it)
NSMutableArray * favoriteCounts = [NSMutableArray array];
for (id user in counts) {
[favoriteCounts addObject:[NSDictionary dictionaryWithObjectsAndKeys:
user, @"user",
[NSNumber numberWithUnsignedInteger:[counts countForObject:user]], @"count",
nil]];
}
//sort the dictionary by the count, descending
[favoriteCounts sortUsingDescriptors:[NSArray arrayWithObject:[[[NSSortDescriptor alloc] initWithKey:@"count" ascending:NO] autorelease]]];
//create a request to fetch all the user objects
request = [[SKFetchRequest alloc] init];
[request setEntity:[SKUser class]];
[request setPredicate:[NSPredicate predicateWithFormat:@"%K = %@", SKUserID, [favoriteCounts valueForKey:@"user"]]];
NSArray * users = [site executeSynchronousFetchRequest:request error:nil];
[request release];
//build a userID => user map
NSDictionary * userMapping = [NSDictionary dictionaryWithObjects:users forKeys:[users valueForKey:SKUserID]];
//print out the favorited count and username
for (NSDictionary * top in favoriteCounts) {
SKUser * user = [userMapping objectForKey:[top objectForKey:@"user"]];
NSLog(@"%2d - %@ [%@]", [[top objectForKey:@"count"] unsignedIntegerValue], [user displayName], [user userID]);
}