我有这段代码BGBaseSnippetCode.h
:
static NSMutableDictionary * defaultHeightDictionary= nil;
static NSMutableDictionary * defaultBoundsDictionary =nil;
+(void)initialize
{
BGBaseTableViewCell * typical = [[self alloc]init];
if (defaultHeightDictionary==nil) {
defaultHeightDictionary = [NSMutableDictionary dictionary];
defaultBoundsDictionary = [NSMutableDictionary dictionary];
}
[defaultHeightDictionary setValue:@(typical.bounds.size.height) forKey:NSStringFromClass([self class])];
CGRect bounds = typical.bounds;
NSValue * boundsValue = [NSValue valueWithCGRect:bounds];
[defaultHeightDictionary setValue:boundsValue forKey:NSStringFromClass([self class])];
}
+(CGFloat) defaultHeight
{
NSNumber * result = [defaultHeightDictionary valueForKey:NSStringFromClass([self class])];
return result.floatValue;
}
+(CGRect) defaultBounds
{
NSValue * result = [defaultBoundsDictionary valueForKey:NSStringFromClass([self class])];
return [result CGRectValue];
}
我想在BGBaseOfAllUIControl.m
和BGBaseTableViewCell.m
中插入此内容。所以我只是笨拙地做了:
@interface BGBaseOfAllUIControl ()
@property (strong, nonatomic) IBOutlet UIView *view;
@end
@implementation BGBaseOfAllUIControl
#import "BGBaseSnippetCode.h"
-(id)initWithCoder:(NSCoder *)aDecoder
{
self = [super initWithCoder:aDecoder];
if (self) {
[self BaseInitialize];
}
@interface BGBaseTableViewCell ()
@property (strong, nonatomic) IBOutlet UITableViewCell *view;
@end
@implementation BGBaseTableViewCell
//static BOOL isDefaultHeightSet = NO;
#import "BGBaseSnippetCode.h"
-(id)initWithCoder:(NSCoder *)aDecoder
{
self = [super initWithCoder:aDecoder];
if (self) {
[self BaseInitialize];
}
return self;
基本上BGBaseOfAllUIControl
和BGBaseTableViewCell
共享相同的协议,我希望完全相同的代码实现双方的协议。 BGBaseTableViewCell
是UITableViewCell
的子类,BGBaseOfAllUIControl
是UIControl
的子类。
所以我使用.h文件来包含一些实现。代码工作正常。只是尴尬。什么是更好的方法来做到这一点,或者我做得对吗?
答案 0 :(得分:2)
我会忘记所有标头导入和静态字典技巧,并引入一个单独的类来处理您需要的布局信息。类似的东西:
@interface BGTableLayoutInfo
- (float) defaultHeightForClass: (Class) tableViewType;
- (CGRect) defaultBoundsForClass: (Class) tableViewType;
@end
在实现中,您将拥有一个常规(非静态)字典来缓存不同类的布局信息。唯一剩下的问题是表视图对象将如何获取布局类的实例。一种可能性是使布局信息方法静态(使用静态缓存字典),其次是通过+defaultLayoutInfo
方法保持共享实例可访问。