runtime笔记

来源:互联网 发布:知乎自媒体营销模式 编辑:程序博客网 时间:2024/06/17 13:30

想来也是第一次接触runtime,以前在大神的帖子中也能看到runtime,但一直不明白用意。

首先,oc中最重要的元素就是对象。在objc文件中,对象实际上是一个结构体(oc是c的封装)。内部是一个isa指针,这个isa指针指向类对象。

/// Represents an instance of a class.
struct objc_object {
    Class isa  OBJC_ISA_AVAILABILITY;
};

/// A pointer to an instance of a class.

typedef struct objc_object *id;


类:

struct objc_class {
    Class isa  OBJC_ISA_AVAILABILITY;

#if !__OBJC2__
    Class super_class                                        OBJC2_UNAVAILABLE;
    const char *name                                         OBJC2_UNAVAILABLE;
    long version                                             OBJC2_UNAVAILABLE;
    long info                                                OBJC2_UNAVAILABLE;
    long instance_size                                       OBJC2_UNAVAILABLE;
    struct objc_ivar_list *ivars                             OBJC2_UNAVAILABLE;
    struct objc_method_list **methodLists                    OBJC2_UNAVAILABLE;
    struct objc_cache *cache                                 OBJC2_UNAVAILABLE;
    struct objc_protocol_list *protocols                     OBJC2_UNAVAILABLE;
#endif

} OBJC2_UNAVAILABLE;
/* Use `Class` instead of `struct objc_class *` */

在c++中class是个类型,在oc中class是个结构体。其中包含了方法列表,类名,实例变量列表,协议列表等等。其中还有一个isa指针,指向原类对象。原类对象中存放的是类方法。

runtime方法用的较为普遍的是动态添加实例变量。对于类目是无法向类中添加实例变量的。

@interface Person (Extension)

@property (nonatomic, assign)NSInteger age;

@end

@implementation Person (Extension)

- (void)setAge:(NSInteger)age {
    NSNumber *number = [NSNumber numberWithInteger:age];
    objc_setAssociatedObject(self, @"_age", number, OBJC_ASSOCIATION_ASSIGN);
}

- (NSInteger)age {
    return [objc_getAssociatedObject(self, @"_age") integerValue];
}

@end

objc_setAssociatedObject(self, @"_类型名",value, 内存策略)来存储数据,达到向类中添加实例变量的效果。


0 0
原创粉丝点击