2014-10-09 106 views
0

我試圖做一個「朋友」系統在我的應用程序,而當用戶接受好友請求,我都將用戶添加到這樣一個關係:將用戶添加到PFRelation

var cUserRelation = PFUser.currentUser().relationForKey("friendsRelation") as PFRelation 
var senderRelation = sender.relationForKey("friendsRelation") as PFRelation 

cUserRelation.addObject(sender) 
senderRelation.addObject(PFUser.currentUser()) 

PFUser.currentUser.saveInBackground() 
sender.saveInBackground() 

但由於某種原因,它只會將發件人添加到當前用戶的關係中。我該如何解決這個問題?謝謝:)

回答

0

下面是從樹屋的樣本項目,可能會有所幫助:

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { 

[self.tableView deselectRowAtIndexPath:indexPath animated:nil]; 


UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath]; 

// if the current relationKey doesn't exist, it will be create for us. 
PFRelation *friendsRelation = [self.currentUser relationForKey:@"friendsRelation"]; 
// adding users is easy. use addObject methoed then we can pass in the user that was tapped on as the parameter. To get that user, we have to get the indexPath just like we did in the 'cellForRowAtIndexPath' method 
PFUser *user = [self.allUsers objectAtIndex:indexPath.row]; 

if ([self isFriend:user]) 
{ 

    cell.accessoryType = UITableViewCellAccessoryNone; 
    // 2. remove from the array of friends // the only way we have to find a user in an array is to loop through and look for a matching objectid. 
    for (PFUser *friend in self.friends) 
    { 
     if ([friend.objectId isEqualToString:user.objectId]) 
     { 
      [self.friends removeObject:friend]; 
      break; 
     } 
    // 3. Remove from the backend 
     [friendsRelation removeObject:user]; 
     [self.currentUser saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) { 
      NSLog(@"Error %@ %@", error, [error userInfo]); 
     }]; 
    } 
} 
    else 
{ 
    cell.accessoryType = UITableViewCellAccessoryCheckmark; 
    [self.friends addObject:user]; 
    for (PFUser *friend in self.friends) { 
     if ([friend.objectId isEqualToString:user.objectId]) { 
      [self.friends addObject:friend]; 
      break; 
     } 

     // and now we can use the user variable here as the parameter for addObject, which adds the user locally 
     [friendsRelation addObject:user]; 
     // but we also have to add the user on the backend 
     [self.currentUser saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) { 
      if (error) { 
       NSLog(@"Error %@ %@", error, [error userInfo]); 
      } 
     }]; 


    } 
} 
}