Reputation: 31
I have a textfield where users enter a username and click add. Is this the best way to do this?: Make query for name of user. If user does not exist, give warning message. If user does exist, add them to relations with this:
[self.friends addObject:user];
[friendsRelation addObject:user];
Another question is, how do I search for a user with a query and return an object? Also, here are some variables I made in .h
@property (nonatomic, strong) NSArray *allUsers;
@property (nonatomic, strong) PFUser *currentUser;
@property (nonatomic, strong) NSMutableArray *friends;
@property (nonatomic, strong) PFUser *foundUser;
- (BOOL)isFriend:(PFUser *)user;
Upvotes: 0
Views: 245
Reputation: 3291
Check out the below code and you can tailor it to your more specific needs, but it generally does what you are asking for. I strongly advise you to read the documentation on all the methods in the code, and check some Parse tutorials or sample code - they have this covered extensively.
// create and set query for a user with a specific username
PFQuery *query = [PFUser query];
[query whereKey:@"username" equalTo:@"usernameYouWantToAdd"];
// perform the query to find the user asynchronously
[query getFirstObjectInBackgroundWithBlock:^(PFObject *object, NSError *error) {
if (error) {
NSLog(@"Error: %@ %@", error, [error userInfo]);
// the Parse error code for "no such user" is 101
if (error.code == 101) {
NSLog(@"No such user");
}
}
else {
// create a PFUser with the object received from the query
PFUser *user = (PFUser *)object;
[friendsRelation addObject:user];
[self.friends addObject:user];
// save the added relation in the Parse database
[self.currentUser saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
if (error) {
NSLog(@" %@ %@", error, [error userInfo]);
}
}];
}
}];
Note that referencing self
inside the block can lead to a retain cycle and thus a memory leak. To prevent this, you can get create a weak reference to self
outside the block, where ClassOfSelf
is the class of what self
is, in this case most likely your view controller:
__weak ClassOfSelf *weakSelf = self;
And then use it to access self
in the block, for example:
[weakSelf.friends addObject:user];
Upvotes: 1
Reputation: 2338
First, to add a relation I would first get the relation column from the user, addObject on that relation, then just save the user.
Next, what kind of query are you looking for? Do you want to query for the friends of a user? Query the user table for users who are friends with so and so? Could you elaborate?
Upvotes: 0