首页 > 其他 > 详细

自定义NSIndexPath — 給Category添加property

时间:2014-03-20 11:33:31      阅读:550      评论:0      收藏:0      [点我收藏+]

最近需要实现一个卡牌和滑动翻页的效果,考虑和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

自定义NSIndexPath — 給Category添加property,布布扣,bubuko.com

自定义NSIndexPath — 給Category添加property

原文:http://blog.csdn.net/zhoutao198712/article/details/21598911

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!