最近需要实现一个效果,考虑和TableView非常类似,就想把接口实现成和UITableView的接口相似。
首先,需要解决的问题就是需要自定义一个自己的NSIndexPath以使得更加服务语义环境。先看了UITableView的NSIndexPath,他的实现是基于Category的。但是众所周知,Category是不能直接添加Property的,那怎么来解决这个问题呢?
问题的解决办法就是用Objc的动态特性,动态的来关联属性的key和value。先上代码,然后再解释。
NSIndexPath_PageCardView.h
@interface NSIndexPath(GLPageCardView)
@property (nonatomic,assign) NSInteger page;
@property (nonatomic,assign) NSInteger card;
+(NSIndexPath*)indexPathForCard:(NSInteger)card inPage:(NSInteger)page;
@end
NSIndexPath_PageCardView.m
#import <objc/runtime.h>
static const void *Page = &Page;
static const void *Card = &Card;
@implementation NSIndexPath(GLPageCardView)
@dynamic page;
@dynamic card;
-(NSInteger)page
{
return [objc_getAssociatedObject(self, Page) intValue];
}
-(void)setPage:(NSInteger)page
{
NSNumber *number= [[NSNumber alloc] initWithInteger:page];
objc_setAssociatedObject(self, Page, number, OBJC_ASSOCIATION_COPY);
}
-(NSInteger)card
{
return [objc_getAssociatedObject(self, Card) intValue];
}
-(void)setCard:(NSInteger)card
{
NSNumber *number = [[NSNumber alloc] initWithInteger:card];
objc_setAssociatedObject(self, Card, number, OBJC_ASSOCIATION_COPY);
}
+(NSIndexPath*)indexPathForCard:(NSInteger)card inPage:(NSInteger)page
{
NSIndexPath *index =[[NSIndexPath alloc ] init];
[index setCard:card];
[index setPage:page];
return index;
}
@end
关键点:
1、property需要使用dynamic修饰符,使用dynamic修饰符就需要自己手动来实现get和set方法。
2、get方法通过objc_getAssociatedObject来获取。
3、set方法是通过objc_setAssociatedObject来设定。
objc_getAssociatedObject和objc_setAssociatedObject都需要指定一个固定的地址,这个固定的地址值用来表示属性的key,起到一个常量的作用。
我的个人博客地址:自定义NSIndexPath