PFRelation不会在Parse.com上节省

时间:2015-03-06 16:47:31

标签: ios objective-c xcode parse-platform

我在保存PFRelation时遇到问题我有这段代码:

//set up the query
    PFQuery *query = [PFQuery queryWithClassName:@"messageBank"];
    [query whereKey:@"username" equalTo:name];
    __weak User *weakSelf = self;


    [query getFirstObjectInBackgroundWithBlock:^(PFObject *object, NSError *error) {

        if(error) {

            NSLog(@"No such user");
            handler(NO, error,NO,NO);
        }

        else{

            [weakSelf.friendsRelation addObject:object];
            [weakSelf.friends addObject:object];
            //save in the background
            [weakSelf.messageBank saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                if(error) {

                    NSLog(@"Save error");
                }

                else {

                    NSLog(@"no error");
                }
            }];


            handler(YES,nil,NO,NO); //no errors
            //so the friend is added to the friends array, all we need to do is reload the table data don't need to init the array again, the relation is also added to the relation item so don't need to init that again
        }


    }];//end block

我的代码发现messageBank对象很好,但它不会将其保存到PFRelation朋友。它甚至没有尝试拨打[weakSelf.messageBank saveInBackgroundWithBlock...。 weakSelf.messageBank是本地的PFObject,而weakSelf.friends是它的PFRelation。任何人都有任何想法在这里可能会出错?如果我在A类中有PFRelation,那么可以在A类中与其他对象建立关系吗?它需要在不同的班级吗?任何帮助将不胜感激!!!

1 个答案:

答案 0 :(得分:0)

这是一个清理版本的代码,它获取一个对象并添加到它的关系中并保存它......

PFQuery *query = [PFQuery queryWithClassName:@"messageBank"];  // by convention class names should be capital MessageBank, but using yours
[query whereKey:@"username" equalTo:name];  // better form is self.name assuming it is an attribute of self

[query getFirstObjectInBackgroundWithBlock:^(PFObject *object, NSError *error) {
    if (!error) {
        // see note below about weakSelf
        // assume self is a PFObject subclass with two relations
        // (and generated setters) called friendsRelation and friends
        [self.friendsRelation addObject:object];
        [self.friends addObject:object];

        // notice we save self here.  that's who changed in the two preceding lines
        [self saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
            if(!error) {
                // success
            } else {
                // handle error
            }
        }];
    } else {
        // handle error
    }
}];

请注意,不需要声明自我指针的__weak副本(但是,它没有任何伤害)。这个习惯用于避免自我和街区所有者之间的保留周期。只有当self是块所有者(直接或间接)时才需要它。解析完成块不是这种情况。