iOS底层学习-day-11

前言-OC-Rutime篇

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

isa指针

  • 要想学习Runtime,首先要了解它底层的一些常用数据结构,比如isa指针
  • 在arm64架构之前,isa就是一个普通的指针,存储着Class、Meta-Class对象的内存地址
  • 从arm64架构开始,对isa进行了优化,变成了一个共用体(union)结构,还使用位域来存储更多的信息

位域

  • MJPerson.h
#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
  • MJPerson.m
#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

优化后

  • MJPerson.h
#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
  • MJPerson.m
#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

  • 从arm64后,优化了isa,isa是 &isa_max才是指向对象的地址值的,采取共用体的结构,将一个64的结构体数据来储存更多东西,其中的shift_cls33位才是来储存具体的地址值的
发布了12 篇原创文章 · 获赞 0 · 访问量 97

猜你喜欢

转载自blog.csdn.net/weixin_41732253/article/details/103946606
今日推荐