分类(category)的设计

1).类中经常容易填满各种方法,而这些方法的代码则会全部堆在一个巨大的实现文件里。在这种情况下,可以用过OC的分类机制,把类代码按逻辑划入几个分区中

#import 

@interface EOCPerson : NSObject

@property(nonatomic, copy, readonly) NSString *firstName;

- (id)initWithFirstName:(NSString *)firstName;

@end

@interface EOCPerson (Friendship)
- (void)addFriend:(EOCPerson *)person;
@end

@interface EOCPerson (Work)
- (void)performDayWork;
@end
#import "EOCPerson.h"
@interface EOCPerson (Friendship)
- (void)addFriend:(EOCPerson *)person;
@end

#import "EOCPerson+Friendship.h"
@implementation EOCPerson (Friendship)
-(void)addFriend:(EOCPerson *)person
{
}
@end

#import "EOCPerson.h"

@interface EOCPerson (Work)
-(void)performDayWork;
@end

#import "EOCPerson+Work.h"
@implementation EOCPerson (Work)
-(void)performDayWork
{
}
@end

2).如果有一些私有的方法不想公开,可建一个Private的分类,只在实现文件实现不声明,那就可以做到保密性。

3).为分类添加属性。尽管声明了属性,但分类不会为属性设置set/get方法,类似于@dynamic

@interface EOCPerson (Friendship)
@property(nonatomic, strong) NSArray *friends;
- (void)addFriend:(EOCPerson *)person;
@end

#import "EOCPerson+Friendship.h"
#import 

static const char *kFriendsPropertyKey = "kFriendsPropertyKey";

@implementation EOCPerson (Friendship)
-(void)addFriend:(EOCPerson *)person
{
    
}

-(NSArray *)friends
{
    return objc_getAssociatedObject(self, kFriendsPropertyKey);
}

-(void)setFriends:(NSArray *)friends
{
    objc_setAssociatedObject(self, kFriendsPropertyKey, friends, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

@end

你可能感兴趣的:(分类(category)的设计)