如何将其划分为方法

时间:2011-11-04 06:09:29

标签: iphone objective-c ipad

我正在尝试重构我的代码,以便它遵循良好的OO模式,这是可重用性和较少重复..我有以下代码:

 PFQuery * query = [PFQuery queryWithClassName:@"Vote"];
    query.cachePolicy = kPFCachePolicyNetworkElseCache;
    [query whereKey:@"poll" equalTo:self.vote];
    [query whereKey:@"note" notEqualTo:nil];
    [query countObjectsInBackgroundWithBlock:^(int number, NSError * error) {
        note = number;
        [self.noteCount addSubview:self.generateCountLabel];

        if (note > 0){
            [self.note setUserInteractionEnabled:YES];
            [self.note setEnabled:YES];
        }
    }];

    PFQuery * query1 = [PFQuery queryWithClassName:@"Vote"];
    query1.cachePolicy = kPFCachePolicyNetworkElseCache;
    [query1 whereKey:@"poll" equalTo:self.vote];
    [query1 whereKey:@"image" notEqualTo:nil];
    [query countObjectsInBackgroundWithBlock:^(int number, NSError * error) {
        pic = number;    
        [self.picCount addSubview:self.generateCountLabel];

        if (pic > 0){
            [self.pic setUserInteractionEnabled:YES];
            [self.pic setEnabled:YES];
        }

    }];

发现在没有做很多if的情况下分割成一个方法真的很困难。有什么想法吗?

1 个答案:

答案 0 :(得分:3)

您可以使用以下方法....

- (void)queryForKey:(NSString *)aKey view:(UIView *)aView countView:(UIView *)aCountView  {
    PFQuery * query = [PFQuery queryWithClassName:@"Vote"];        
    query.cachePolicy = kPFCachePolicyNetworkElseCache;
    [query whereKey:@"poll" equalTo:self.vote];
    [query whereKey:aKey notEqualTo:nil];
    [query countObjectsInBackgroundWithBlock:^(int number, NSError * error) {
        count = number;    
        [aCountView addSubview:self.generateCountLabel];

        if (count > 0){
            [aView setUserInteractionEnabled:YES];
            [aView setEnabled:YES];
        }
    }];
}

然后你可以打电话......

[self queryForKey:@"note" view:self.note countView:self.noteCount];
[self queryForKey:@"image" view:self.pic countView:self.picCount];

如果你确定你的命名,你可以使用动态对象选择器,即你有@“note”,self.note和self.noteCount的'note',这样你就可以取@“note”并同时选择动态注意和noteCount视图(因为它们都以'note'开头),但是这对你的图像不起作用,因为你有@“image”但是然后是self.pic和self.picCount。

<强>更新

将图像重命名为pic,然后将四个视图(picCount,pic,note和noteCount)公开为属性。然后你可以使用这样的东西......

- (void)queryForKey:(NSString *)aKey  {
    PFQuery * query = [PFQuery queryWithClassName:@"Vote"];        
    query.cachePolicy = kPFCachePolicyNetworkElseCache;
    [query whereKey:@"poll" equalTo:self.vote];
    [query whereKey:aKey notEqualTo:nil];
    [query countObjectsInBackgroundWithBlock:^(int number, NSError * error, NSString *aKey) {
        [self setValue:number forKey:aKey];
        UIView *countView = [self objectForKey:[NSString stringWithFormat:@"%@Count", aKey]];
        [countView addSubview:self.generateCountLabel];

        if (number > 0){
            UIView *mainView = [self objectForKey:aKey];
            [mainView setUserInteractionEnabled:YES];
            [mainView setEnabled:YES];
        }
    }];
}

你将不得不玩它,因为我没有完整的类定义来完全正确。