美文网首页
(二十三) [OC高效系列]将类的实现代码分散于便于管理的数个分

(二十三) [OC高效系列]将类的实现代码分散于便于管理的数个分

作者: 修行猿 | 来源:发表于2016-08-19 19:51 被阅读40次

1.如题,比如这样,将基本要素等声明放在主实现中,执行不同的操作所用的另外几套方法则归入各个分类中。

头文件

@interface Person : NSObject <NSCopying>
@property (nonatomic,copy) NSString *name;
@property (nonatomic,readonly) NSArray *friends;
@property (nonatomic,assign) int age;
@end

@interface Person (FriendShip)
- (void)addFriend:(Person *)person;
- (void)removeFriend:(Person *)person;
@end

@interface Person (Play)
- (void)playPingPong;
- (void)playFootball;
- (void)sing;
- (void)run;
@end

实现文件

@interface Person ()
@property (nonatomic,readwrite,strong) NSMutableArray *friends;
@end
@implementation Person
- (instancetype)initWithName:(NSString *)name age:(int)age
{
    self = [super init];
    if (self) {
        self.name = name;
        self.age = age;
        _friends = [NSMutableArray array];
    }
    return self;
}

- (NSArray *)friends{
    return [_friends copy];
}

- (id)copyWithZone:(NSZone *)zone{
    Person *p = [[[self class] allocWithZone:zone] initWithName:_name age:_age];
    p->_friends = [_friends mutableCopy];
    return p;
}
@end

@implementation Person (FriendShip)
- (void)addFriend:(Person *)person{
    if(person){
        [_friends addObject:person];
    }
}
- (void)removeFriend:(Person *)person{
    if(person){
        [_friends removeObject:person];
    }
}
@end
@implementation Person (Play)
- (void)playPingPong {
}
- (void)playFootball {
}
- (void)sing{
}
- (void)run{
}
- (void)eat{
}
@end

2.这样的好处

  • 易于管理,方便检视
  • 分类名称会出现在符号信息中


    Paste_Image.png

3.将视为私有的方法归入名叫private的分类中,以隐藏其细节。

  • 在编写分享给其他开发者使用的程序库时,可以考虑创建Private的分类。经常会遇到这样的一些方法:他们不是公共API的一部分,然而却非常适合在程序库之内使用。此时应该创建Private分类,如果程序库中某个地方要用到这些方法,就引入这个分类的头文件。而分类的头文件并不随程序库一并公开,于是该库的使用者并不知道这些方法。
  • 如果调用者通过其他方式调用,在调试器中看到Private一词,便知道不能直接调用。

相关文章

网友评论

      本文标题:(二十三) [OC高效系列]将类的实现代码分散于便于管理的数个分

      本文链接:https://www.haomeiwen.com/subject/hjmbsttx.html