Skip to content

Instantly share code, notes, and snippets.

@pxpgraphics
Created December 4, 2014 02:17
Show Gist options
  • Save pxpgraphics/4f1055ef78c2ed90542e to your computer and use it in GitHub Desktop.
Save pxpgraphics/4f1055ef78c2ed90542e to your computer and use it in GitHub Desktop.
Parse: PFObject favorite methods
@implementation
/*...*/
- (void)toggleFavorite:(BOOL)isFavorite
{
PFUser *user = [PFUser currentUser];
if (!user) {
return;
}
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
NSArray *favorites = [userDefaults objectForKey:kDefaultsFavoriteKey];
BOOL contains = [self isFavorite];
if (!(contains ^ isFavorite)) {
return; // Status quo is fine; the UI shouldn't have allowed this case in the first place.
}
NSNotification *notification;
if (isFavorite) {
if (favorites) {
favorites = [favorites arrayByAddingObject:self.objectId];
} else {
favorites = @[ self.objectId ];
}
PFRelation *favoritesRelation = [user relationForKey:@"favorite{Object}s"];
[favoritesRelation addObject:self];
[user saveEventually];
notification = [NSNotification notificationWithName:Favorite{Object}AddedNotification object:self];
} else {
favorites = [favorites filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(NSString *objectId, NSDictionary *bindings) {
return ![objectId isEqualToString:self.objectId];
}]];
PFRelation *favoritesRelation = [user relationForKey:@"favorite{Object}s"];
[favoritesRelation removeObject:self];
[user saveEventually];
notification = [NSNotification notificationWithName:Favorite{Object}RemovedNotification object:self];
}
[userDefaults setObject:favorites forKey:kDefaultsFavoriteKey];
[userDefaults synchronize];
[[NSNotificationCenter defaultCenter] postNotification:notification];
}
- (BOOL)isFavorite
{
NSSet *favorites = [NSSet setWithArray:[[NSUserDefaults standardUserDefaults] objectForKey:kDefaultsFavoriteKey]];
return [favorites containsObject:self.objectId];
}
/*...*/
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment