查看下面的代码,您可以根据您更具体的需求对其进行定制,但它通常可以满足您的要求。我强烈建议您阅读有关代码中所有方法的文档,并查看一些 Parse 教程或示例代码 - 他们对此进行了广泛的介绍。
// 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]);
}
}];
}
}];
请注意,self
在块内引用可能会导致保留周期,从而导致内存泄漏。为了防止这种情况,您可以创建self
对块外部的弱引用,其中ClassOfSelf
的类是什么self
,在这种情况下很可能是您的视图控制器:
__weak ClassOfSelf *weakSelf = self;
然后在块中使用它来访问self
,例如:
[weakSelf.friends addObject:user];