如何以面向对象的方式将参数传递给控制器

时间:2014-06-18 11:33:42

标签: objective-c oop object-oriented-analysis

单击照片时,我会检查它的类别并调用http请求函数和 根据照片类别配置其参数。这是一个简化的代码:

- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    Item *item = (Item *) [self.recentItems objectAtIndex:indexPath.row];

    if ( [item.Type  isEqual: @"typeA"] ) {
         connectionProperties.P1 = "A1"
         connectionProperties.P2 = "A2"
    }
    else if ( [item.Type  isEqual: @"typeB"] ){
         connectionProperties.P1 = "B1"
         connectionProperties.P3 = "B2"
         connectionProperties.P4 = "B3"
    }
 }

   albumDataController = [[AlbumDataController alloc] initWithConnectionProperty:connectionProperties andCommunicator:self.comm];


[albumDataController fetchItemsForCategory:category
            ItemsSuccess:^(Album *album) {

                photos = [[NSArray alloc] initWithArray:album.photos];

                PhotoViewController *photoViewController = [[PhotoViewController alloc] initWithPhotos:photos];


                [self presentViewController: photoViewController animated:YES completion:nil];


            }

}

我知道这不是面向对象的方式。我应该如何以面向对象的方式实现这一点。

1 个答案:

答案 0 :(得分:1)

面向对象的方法是让Item的子类创建自己的连接属性(或者更好的是具有Item协议,因为Objective-C没有抽象方法)。

示例:

@interface Item : NSObject
- (ConnectionProperties *)connectionProperties;
@end

@implementation Item

- (ConnectionProperties *)connectionProperties
{
    [self doesNotRecognizeSelector:_cmd];
    return nil;
}

@end

@interface ItemA : Item
@end

@implementation ItemA

- (ConnectionProperties *)connectionProperties
{
    ConnectionProperties *connectionProperties = [[ConnectionProperties alloc] init];
    connectionProperties.P1 = "A1";
    connectionProperties.P2 = "A2";
    return connectionProperties;
}

@end

@interface ItemB : Item
@end

@implementation ItemB

- (ConnectionProperties *)connectionProperties
{
    ConnectionProperties *connectionProperties = [[ConnectionProperties alloc] init]; 
    connectionProperties.P1 = "B1"
    connectionProperties.P3 = "B2"
    connectionProperties.P4 = "B3"
    return connectionProperties;
}

@end

这样您的代码就不需要知道项目的内部结构了:

- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    Item *item = (Item *) [self.recentItems objectAtIndex:indexPath.row];

    albumDataController = [[AlbumDataController alloc] initWithConnectionProperty:item.connectionProperties andCommunicator:self.comm];

使用协议将类似:

@protocol Item <NSObject>
- (ConnectionProperties *)connectionProperties;
...
@end