读EffectiveObjective-C2.0(第一条、第二条

2020-10-15  本文已影响0人  LazyLoad

第一条:了解Objective-C语言的起源

第二条:在类的头文件中尽量少引用其他头文件

// EOCPerson.h
#import <Foundation/Foundation.h>

NS_ASSUME_NONNULL_BEGIN

@interface EOCPerson : NSObject
@property (nonatomic, copy) NSString *firstName;
@property (nonatomic, copy) NSString *lastName;
@end

NS_ASSUME_NONNULL_END
  
// EOCPerson.m
#import "EOCPerson.h"
@implementation EOCPerson

@end
// EOCPerson.h
#import <Foundation/Foundation.h>

NS_ASSUME_NONNULL_BEGIN

@interface EOCPerson : NSObject
@property (nonatomic, copy) NSString *firstName;
@property (nonatomic, copy) NSString *lastName;
@property (nonatomic, strong) EOCEmployer *employer;
@end

NS_ASSUME_NONNULL_END
#import "EOCEmployer.h"
// EOCPerson.h
#import <Foundation/Foundation.h>
@class EOCEmployer;

NS_ASSUME_NONNULL_BEGIN

@interface EOCPerson : NSObject
@property (nonatomic, copy) NSString *firstName;
@property (nonatomic, copy) NSString *lastName;
@property (nonatomic, strong) EOCEmployer *employer;
@end

NS_ASSUME_NONNULL_END
// EOCPerson.m
#import "EOCPerson.h"
#import "EOCEmployer.h"

@implementation EOCPerson
- (void)setEmployer:(EOCEmployer *)employer {
    _employer = employer;
    _firstName = employer.nickName;
}
@end

将引入头文件的时机尽量延后,在确实需要使用的时候引入,这样可以减少类的使用者所需引入头文件的数量。假设把EOCEmployer.h的头文件引入到EOCPerson.h,那么其他文件引入EOCPerson.h就会一并引入EOCEmployer.h的全部内容,而其他文件不需要用到EOCEmployer.h中的内容,这么延续下去的话,会引入许多额外的没有用的头文件,就会增加编译时间。

- (void)addEmployee:(EOCPerson *)person;
- (void)removeEmployee:(EOCPerson *)person;
上一篇下一篇

猜你喜欢

热点阅读