是否可以隐藏类的继承?

时间:2014-01-07 19:05:18

标签: ios objective-c

从外面我希望我的班级能够像这样出现

@interface MYCardGroupView : UIView
@property (nonatomic, strong) NSArray *cardObjects;
@end

但是在类本身中我希望它实际上是一个UITableView

@interface MYCardGroupView : UITableView <UITableViewDataSource, UITableViewDelegate>
@property (nonatomic, strong) NSArray *cardObjects;
@end

参数:

  • 从API的角度来看,仅显示必要的界面
  • 是有意义的
  • 将UITableView作为子视图只是为了保持界面不显示(干净的界面与具有更深层视图树的性能成本)感觉非常过分。

5 个答案:

答案 0 :(得分:4)

理论上,人们可以使用两个单独的.h文件,一个是“真正的”文件,只命名为“MyClass_real.h”,另一个是假的,命名为“MyClass.h”。在.m中包含真实的那个,但使用假的那个作为广告界面。假的可以说你的基类是“马铃薯”,它没有任何区别。

(我猜想,人们不得不担心ARC。可能会感到不安。)

答案 1 :(得分:2)

您可以通过将它们添加到.m文件中的类扩展名来隐藏它实现的协议(如UITableViewDataSourceUITableViewDelegate)。但你无法隐藏它是一个UITableView子类。

然而,有一个额外的UIView不应该损害性能,至少不是以任何明显的方式。在内置的UIKit元素中,您没有注意到额外的视图,影响可能非常小。如果您担心性能,请将其保留为UITableView子类。但是如果你不是那么担心而且你更关心隐藏的东西,那就把它变成一个UIView子类,让它封装一个UITableView。

答案 2 :(得分:2)

您可以在标头之外声明协议(通过类扩展 - 未命名的类别),但技术上不是继承。那是因为通常你想要知道继承。

立即明显的解决方法包括:

  • 声明属于UIView的子类的公共类,使其initalloc替换另一个类的实例,否则该实例遵循相同的已发布接口但是{ {1}};和
  • 使用已弃用的class_setSuperclass(从第一天开始弃用但仍然可用)在UITableViewController更改您的超类。

答案 3 :(得分:1)

你所追求的实际上是一个类集群,集群大小为1 - 不寻常但可能非常合法。

标准框架中的许多类;例如NSString;实现为 clusters ,其中公共类是“抽象”(不是传统的OO意义),一个或多个私有类提供实际的实现。在创建公共类的实例时,其init(或alloc)替换其中一个私有类的实例。

这是Cocoa中定义良好的模型,请参阅Apple的Cocoa Core Competencies: Class Cluster

答案 4 :(得分:0)

这从功能角度来看,但有以下缺点

  • +[MYCardGroupView alloc]Incompatible pointer types returning 'MYPrivateCardGroupView *' from a function with result type 'MYCardGroupView *'
  • 中抛出错误
  • 必须宣布一切两次的额外工作

.H-文件

@interface MYCardGroupView : UIView
@property (nonatomic, strong) NSArray *cardObjects;
@end

的.m文件

#import "MYCardGroupView.h"

@interface MYPrivateCardGroupView : UITableView <UITableViewDataSource, UITableViewDelegate>
@property (nonatomic, strong) NSArray *cardObjects;
@end

@implementation MYCardGroupView

+ (id)alloc
{
    return [MYPrivateCardGroupView alloc];
}

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if(self)
    {
        NSLog(@"My class is %@", [self class]);
    }
    return self;
}

@end

@implementation MYPrivateCardGroupView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if(self)
    {
        NSLog(@"My class is %@", [self class]);
    }
    return self;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 10;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
    cell.textLabel.text = @"hello";
    return cell;
}

@end

日志

My class is MYPrivateCardGroupView
相关问题