Created
December 4, 2014 02:17
-
-
Save pxpgraphics/4f1055ef78c2ed90542e to your computer and use it in GitHub Desktop.
Parse: PFObject favorite methods
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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