以下のコードを確認してください。より具体的なニーズに合わせて調整できますが、通常は求めていることを実行します。コード内のすべてのメソッドに関するドキュメントを読み、いくつかの 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];