I have this snippet of code, 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];
}
I want to insert this in both BGBaseOfAllUIControl.m and BGBaseTableViewCell.m. So I just did that awkwardly:
@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;
Basically both BGBaseOfAllUIControl and BGBaseTableViewCell share the same protocol and I want the exact same code implement the protocol for both side. The BGBaseTableViewCell is a subclass of UITableViewCell and BGBaseOfAllUIControl is a subclass of UIControl.
So I am using .h files to include some implementation. Codes work fine. Just awkward. What would be a better way to do this, or am I doing this right?
I would forget all the header imports and static dictionary trickery and introduce a separate class that would take care of the layout information you need. Something like:
In the implementation you’d have a regular (not static) dictionary for caching the layout information for different classes. The only remaining issue is how the table view objects are going to get an instance of the layout class. One possibility is to make the layout info methods static (using a static caching dictionary), second is to keep a shared instance accessible via a
+defaultLayoutInfomethod.