自定义NSIndexPath — 給Category添加property

为了实现类似UITableView的效果并提供语义化的接口,博主通过Objective-C的动态特性解决了Category无法直接添加Property的问题。文章详细介绍了如何使用dynamic修饰符以及objc_getAssociatedObject和objc_setAssociatedObject方法来动态关联属性的key和value,从而在NSIndexPath的Category中添加自定义属性。
摘要由CSDN通过智能技术生成

最近需要实现一个效果,考虑和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

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值