其他分享
首页 > 其他分享> > iOS底层学习-day-11

iOS底层学习-day-11

作者:互联网

iOS底层学习-day-11

前言-OC-Rutime篇

我是一名iOS开发者, iOS底层 菜鸟的进阶之路30天。

isa指针

位域

#import <Foundation/Foundation.h>

@interface MJPerson : NSObject

- (void)setTall:(BOOL)tall;
- (void)setRich:(BOOL)rich;
- (void)setHandsome:(BOOL)handsome;

- (BOOL)isTall;
- (BOOL)isRich;
- (BOOL)isHandsome;

@end
#import "MJPerson.h"

#define MJTallMask (1<<0) 0b 0000 0001
#define MJRichMask (1<<1) 0b 0000 0010
#define MJHandsomeMask (1<<2) 0b 0000 0100

@interface MJPerson()
{
    char _tallRichHansome;
}
@end

@implementation MJPerson

- (instancetype)init {
    if (self = [super init]) {
        _tallRichHansome = 0b00000100;
    }
    return self;
}

- (void)setTall:(BOOL)tall {
    if (tall) {
        _tallRichHansome = _tallRichHansome | MJTallMask;
    } else {
        _tallRichHansome = _tallRichHansome & ~MJTallMask;
    }
}

- (BOOL)isTall {
    return !!(_tallRichHansome & MJTallMask);
}

- (void)setRich:(BOOL)rich {
    if (rich) {
        _tallRichHansome |= MJRichMask;
    } else {
        _tallRichHansome &= ~MJRichMask;
    }
}

- (BOOL)isRich {
    return !!(_tallRichHansome & MJRichMask);
}

- (void)setHandsome:(BOOL)handsome {
    if (handsome) {
        _tallRichHansome |= MJHandsomeMask;
    } else {
        _tallRichHansome &= ~MJHandsomeMask;
    }
}

- (BOOL)isHandsome {
    return !!(_tallRichHansome & MJHandsomeMask);
}

@end

优化后

#import <Foundation/Foundation.h>

@interface MJPerson : NSObject

- (void)setTall:(BOOL)tall;
- (void)setRich:(BOOL)rich;
- (void)setHandsome:(BOOL)handsome;

- (BOOL)isTall;
- (BOOL)isRich;
- (BOOL)isHandsome;

@end
#import "MJPerson.h"

@interface MJPerson()
{
    // 位域
    struct {
        char tall : 1;
        char rich : 1;
        char handsome : 1;
    } _tallRichHandsome; //0b 0000 0 handsome rich tall
}
@end

@implementation MJPerson

- (void)setTall:(BOOL)tall {
    _tallRichHandsome.tall = tall;
}

- (BOOL)isTall {
    return !!_tallRichHandsome.tall;
}

- (void)setRich:(BOOL)rich {
    _tallRichHandsome.rich = rich;
}

- (BOOL)isRich {
    return !!_tallRichHandsome.rich;
}

- (void)setHandsome:(BOOL)handsome {
    _tallRichHandsome.handsome = handsome;
}

- (BOOL)isHandsome {
    return !!_tallRichHandsome.handsome;
}

@end

isa_max

林大帅6688 发布了12 篇原创文章 · 获赞 0 · 访问量 65 私信 关注

标签:11,MJPerson,void,iOS,BOOL,rich,isa,day,handsome
来源: https://blog.csdn.net/weixin_41732253/article/details/103946606