0

我有一个文本字段,用户在其中输入用户名并单击添加。这是最好的方法吗?:查询用户名。如果用户不存在,则给出警告信息。如果用户确实存在,请将它们添加到与此的关系中:

    [self.friends addObject:user];
    [friendsRelation addObject:user];

另一个问题是,如何通过查询搜索用户并返回对象?另外,这是我在 .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;
4

2 回答 2

1

查看下面的代码,您可以根据您更具体的需求对其进行定制,但它通常可以满足您的要求。我强烈建议您阅读有关代码中所有方法的文档,并查看一些 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];
于 2014-08-05T17:58:19.590 回答
0

首先,要添加关系,我首先从用户那里获取关系列,在该关系上添加对象,然后保存用户。

接下来,您在寻找什么样的查询?是否要查询用户的好友?在用户表中查询与某某为好友的用户?你能详细说明一下吗?

于 2014-08-05T17:55:15.183 回答