属性

从属性的面试题来发现属性中的一些基本概念

@property 后面可以有哪些修饰符(属性特质)?
  • 原子性(atomic 和 nonatomic)
    原子性的概念 : 在并发编程中,如果说某操作具备完整性,也就是说,系统其它不发无法观察到其中步骤所生成的临时结果,而只能看到操作前和操作后的结果,那么该操作就是原子的(atomic)
  1. atomic原子性,nonatomic非原子性
  2. atomic保证系统自动生成的set和get操作的完整性,在多线程操作属性时,atomic会在setter赋值时加同步锁,保证多线程对setter的重复访问赋值。当一个线程调用setter,其他线程就要等待这个线程完成setter。但是atomic并不就是线程安全的,他只是保证getter和setter存取方法的线程安全。
  3. nonatomic线程不安全,但是换取来的是效率和性能。
  4. 默认的特质为atomic
  • (读/写)权限
    1 readwrite(读写),拥有getter和setter。如果属性由@synthesize实现,则编译器会自动生成这两个方法。
    2 readonly(只读),如果属性由@synthesize实现,编译器会为其合成getter方法。可以使用这个特质在.h文件,即对外公开为只读属性。然后在类拓展中重新定义为读写属性。保证.m内部可修改。
    .h文件中
#import <UIKit/UIKit.h>

@interface ViewController : UIViewController

@property (nonatomic, copy, readonly) NSArray *testArray;

@end

在.m文件声明可读写

@interface ViewController ()
 // 定时器
@property (nonatomic, copy, readwrite) NSArray *testArray;

@end
  • 内存管理
  1. assign: 用于基本数据类型。CGFloat,NSInteger等
  2. strong: 强引用,会使引用计数+1.setter方法赋值时,会保留新值,并释放旧值,然后在将新值设置。
  3. weak: 弱引用,引用计数不增加。setter方法赋值时,即不保留新值,也不释放旧值。当对象被销毁时,属性值会自动置nil。
  4. unsafe_unretained,作用于OC对象,引用计数不增加。当对象被销毁时,属性值不会清空,正如字面上的意思,不安全。
  5. copy,引用计数会+1.然而设置新值并不会保留旧值,而是将其拷贝。
NSString对象为什么尽量用copy来修饰?

我们通过代码查看copy和strong修饰的区别

  • 测试打印不可变字符串情况
#import "ViewController.h"

@interface ViewController ()

// copy字符串
@property (nonatomic, copy) NSString *myCopyStr;
// 强引用str
@property (nonatomic, strong) NSString *strongStr;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
   NSString *testStr = @"测试";
    self.myCopyStr = testStr;
    self.strongStr = testStr;
    
    NSLog(@"testStr : 指针地址 %p", testStr);
    NSLog(@"myCopyStr : 指针地址 %p", _myCopyStr);
    NSLog(@"strongStr : 指针地址 %p", _strongStr);
    
    // Do any additional setup after loading the view, typically from a nib.
}

打印结果

2018-07-17 14:45:05.984532+0800 property[51754:5800611] testStr : 指针地址 0x103a03078
2018-07-17 14:45:05.984738+0800 property[51754:5800611] myCopyStr : 指针地址 0x103a03078
2018-07-17 14:45:05.984863+0800 property[51754:5800611] strongStr : 指针地址 0x103a03078

我们可以看出,三个字符串对应的地址是同一个的。改变一个会导致其他字符串改变。但是现在字符串是不可变的。

  • 测试打印可变字符串情况
#import "ViewController.h"

@interface ViewController ()

// copy字符串
@property (nonatomic, copy) NSString *myCopyStr;
// 强引用str
@property (nonatomic, strong) NSString *strongStr;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    NSMutableString *testStr = [[NSMutableString alloc] initWithString:@"测试"];
//    NSString *testStr = @"测试";
    self.myCopyStr = testStr;
    self.strongStr = testStr;
    
    NSLog(@"testStr : 指针地址 %p", testStr);
    NSLog(@"myCopyStr : 指针地址 %p", _myCopyStr);
    NSLog(@"strongStr : 指针地址 %p", _strongStr);
    
    NSLog(@"----------------------------------------------------");
    [testStr appendString:@"sss"];
    NSLog(@"testStr : 指针地址 %p ,内容%@", testStr , testStr);
    NSLog(@"myCopyStr : 指针地址 %p ,内容%@", _myCopyStr,_myCopyStr);
    NSLog(@"strongStr : 指针地址 %p ,内容%@", _strongStr,_strongStr);
    
    // Do any additional setup after loading the view, typically from a nib.
}

打印

2018-07-17 14:52:35.066351+0800 property[51796:5806435] testStr : 指针地址 0x600000253c20
2018-07-17 14:52:35.066535+0800 property[51796:5806435] myCopyStr : 指针地址 0x600000037d40
2018-07-17 14:52:35.066662+0800 property[51796:5806435] strongStr : 指针地址 0x600000253c20
2018-07-17 14:52:35.066793+0800 property[51796:5806435] ----------------------------------------------------
2018-07-17 14:52:35.067159+0800 property[51796:5806435] testStr : 指针地址 0x600000253c20 ,内容测试sss
2018-07-17 14:52:35.067315+0800 property[51796:5806435] myCopyStr : 指针地址 0x600000037d40 ,内容测试
2018-07-17 14:52:35.067464+0800 property[51796:5806435] strongStr : 指针地址 0x600000253c20 ,内容测试sss

我们可以看出: 通过strong修饰的字符串,strongStrtestStr指向同一块内存地址,testStr修改对应的值,也会相对应修改了strong修饰的字符串strongStr。而copy是重新拷贝了一份,申请了一块独立的内存,无法被影响。

什么情况使用 weak 关键字,相比 assign 有什么不同?
  1. weak用于OC对象,assign用于基本数据类型。
  2. weak会在对象销毁时,将对象置为nil。这样weak修饰的属性发送消息就不会导致野指针操作crash。
__block vs __weak
  1. _block对象可以在block中被重新赋值,__block可以用来修饰OC对象类型,也可以修饰基本数据类型
  2. block中经常出现循环引用,可以通过__weak来避免循环引用。__weak修饰与OC类型对象。
  • __weak一般如下使用
__weak typeof(self) weakSelf = self;
  • YYCategories的YYCategoriesMacro.h中声明了一个宏,简便使用
#ifndef weakify
    #if DEBUG
        #if __has_feature(objc_arc)
        #define weakify(object) autoreleasepool{} __weak __typeof__(object) weak##_##object = object;
        #else
        #define weakify(object) autoreleasepool{} __block __typeof__(object) block##_##object = object;
        #endif
    #else
        #if __has_feature(objc_arc)
        #define weakify(object) try{} @finally{} {} __weak __typeof__(object) weak##_##object = object;
        #else
        #define weakify(object) try{} @finally{} {} __block __typeof__(object) block##_##object = object;
        #endif
    #endif
#endif

#ifndef strongify
    #if DEBUG
        #if __has_feature(objc_arc)
        #define strongify(object) autoreleasepool{} __typeof__(object) object = weak##_##object;
        #else
        #define strongify(object) autoreleasepool{} __typeof__(object) object = block##_##object;
        #endif
    #else
        #if __has_feature(objc_arc)
        #define strongify(object) try{} @finally{} __typeof__(object) object = weak##_##object;
        #else
        #define strongify(object) try{} @finally{} __typeof__(object) object = block##_##object;
        #endif
    #endif
#endif
XIB控件使用weak的原因
  • 从xib上创建控件,在控件放在view上的时候,已经形成了如下的强引用关系:
    UIViewController->UIView->subView->xib控件
    所以你声明的属性对它是弱引用
  • Apple已经对Xib和Storyboard文件做了很多优化。并且由于这些优化,你现在可以将IBOutlet定义为strong,而不是weak。参见文章
怎么用 copy 关键字?

NSString、NSArray、NSDictionary 等等经常使用copy关键字,是因为他们有对应的可变类型:NSMutableString、NSMutableArray、NSMutableDictionary。他们之间可能进行赋值操作,为确保对象中的字符串值不会无意间变动,应该在设置新属性值时拷贝一份。

1>. 因为父类指针可以指向子类对象,使用 copy 的目的是为了让本对象的属性不受外界影响,使用 copy 无论给我传入是一个可变对象还是不可对象,我本身持有的就是一个不可变的副本。
2>. 如果我们使用是 strong ,那么这个属性就有可能指向一个可变对象,如果这个可变对象在外部被修改了,那么会影响该属性。

block 也经常使用 copy 关键字
block 使用 copy 是从 MRC 遗留下来的“传统”,在 MRC 中,方法内部的 block 是在栈区的,使用 copy 可以把它放到堆区.在 ARC 中写不写都行:对于 block 使用 copy 还是 strong 效果是一样的,但写上 copy 也无伤大雅,还能时刻提醒我们:编译器自动对 block 进行了 copy 操作。如果不写 copy ,该类的调用者有可能会忘记或者根本不知道“编译器会自动对 block 进行了 copy 操作”,他们有可能会在调用之前自行拷贝属性值。这种操作多余而低效。

block内部没有调用外部变量时存放在全局区(ARC和MRC下均是)
block使用了外部变量,这种情况也正式我们平时所常用的方式,Block的内存地址显示在栈区,栈区的特点就是创建的对象随时可能被销毁,一旦被销毁后续再次调用空对象就可能会造成程序崩溃,在对block进行copy后,block存放在堆区.所以在使用Block属性时使用Copy修饰,而在ARC模式下,系统也会默认对Block进行copy操作

这个写法会出什么问题: @property (copy) NSMutableArray *array;
  • 首先,原子性特质默认使用的是atomic,会影响性能。atomic底层加入了同步锁加锁机制,保证多线程在setter和getter重复访问。但是这样并不能真正的线程安全。通过声明nonatomic可以去除不必要的性能开销。
  • 内存管理语义特质会影响在setter方法时,对新值和旧值的处理。copy修饰符在setter方法时,并不保留新值,而是将其拷贝。这意味着如果你通过访问实例变量赋值,直接将值赋值给底层实例变量。你可能会察觉不到copy修饰符是错误的。
    代码测试
#import "ViewController.h"

@interface ViewController ()
 // 测试只有copy的情况
@property (copy) NSMutableArray *array;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    NSMutableArray *dataArray = [NSMutableArray arrayWithObjects:@"a",@"b",@"c", nil];
// 直接通过实例变量赋值
    _array = dataArray;
    [dataArray removeObjectAtIndex:0];
    
    NSLog(@"地址1=%p, 地址2=%p, array = %@",dataArray,_array, _array);
    [self.array removeAllObjects];
}

打印

2018-07-18 10:12:46.025498+0800 property[61250:6084862] 地址1=0x600000256530, 地址2=0x600000256530, array = (
    b,
    c
)

顺查看了array赋值后的数据结构

屏幕快照 2018-07-18 上午10.45.06.png

我们可以发现直接通过实例变量赋值,array是一个可变数组。array直接跳过了copy的内存管理语义,默认strong修饰符,array和局部变量dataArray指向同一块地址,array的值会被局部变量dataArray修改所修改。

  • 使用点语法调用setter赋值。
#import "ViewController.h"

@interface ViewController ()

// copy字符串
@property (nonatomic, copy) NSString *myCopyStr;
// 强引用str
@property (nonatomic, strong) NSString *strongStr;

 // 测试只有copy的情况
@property (copy) NSMutableArray *array;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    NSMutableArray *dataArray = [NSMutableArray arrayWithObjects:@"a",@"b",@"c", nil];
// 点语法触发setter赋值
    self.array = dataArray;
    [dataArray removeObjectAtIndex:0];
    
    NSLog(@"地址1=%p, 地址2=%p, array = %@",dataArray,_array, _array);
    [self.array removeAllObjects];
}

我们可以查看赋值后的数据结构


屏幕快照 2018-07-18 上午11.12.34.png

我们可以看出setter赋值后,数组变成了不可变数组NSArrayI。

去除断点打印

2018-07-18 11:15:56.713236+0800 property[64935:6128968] 地址1=0x60400044b4c0, 地址2=0x60400044b880, array = (
    a,
    b,
    c
)
2018-07-18 11:15:56.714139+0800 property[64935:6128968] -[__NSArrayI removeAllObjects]: unrecognized selector sent to instance 0x60400044b880
2018-07-18 11:15:56.725685+0800 property[64935:6128968] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSArrayI removeAllObjects]: unrecognized selector sent to instance 0x60400044b880'

我们可以看出,copy重新生成了一块内存地址,所以局部变量dataArray数据改变并不会影响到array。但是copy生成的数组array变成了不可变数据,但是编译器还是可以调用NSMutableArray的改变数组方法,导致奔溃。

@synthesize和@dynamic分别有什么作用

@synthesize 的语义是如果你没有手动实现 setter 方法和 getter 方法,那么编译器会自动为你加上这两个方法。

@dynamic 告诉编译器:属性的 setter 与 getter 方法由用户自己实现,不自动生成。
我们同样也测试一下

#import <Foundation/Foundation.h>

@interface Person : NSObject<NSCopying>
 // 姓名
@property (nonatomic, strong) NSString *name;
 // 年龄
@property (nonatomic, assign) NSInteger age;

/**
 初始化

 @param name 姓名
 @param age 年龄
 @return <#return value description#>
 */
- (instancetype)initWithName:(NSString *)name age:(NSInteger)age;

@end




#import "Person.h"

@implementation Person

@synthesize name;;

- (instancetype)initWithName:(NSString *)name age:(NSInteger)age {
    if (self = [super init]) {
        self.name = name;
        self.age = age;
    }
    return self;
}

- (id)copyWithZone:(NSZone *)zone {
    Person *person = [[self copyWithZone:zone] initWithName:self.name age:self.age];
    return person;
}

@end
Person *person = [[Person alloc] initWithName:@"sss" age:18];
NSLog(@"name = %@",person.name);

打印结果

2018-07-18 14:13:53.500869+0800 property[65353:6225950] name = sss

但是我们声明为@dynamic name;时,控制台输出

2018-07-18 14:17:50.984929+0800 property[65396:6230197] -[Person setName:]: unrecognized selector sent to instance 0x600000007a70
2018-07-18 14:17:50.993217+0800 property[65396:6230197] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[Person setName:]: unrecognized selector sent to instance 0x600000007a70'

我们可以看出person没有setter方法,@dynamic不会自动合成setter,getter方法。

@synthesize合成实例变量的规则是什么?假如property名为foo,存在一个名为_foo的实例变量,那么还会自动合成新变量么?
  • 通过@synthesize name = myName;指定合成出来的实例变量名
Person *person = [[Person alloc] initWithName:@"sss" age:18];
  
    unsigned int count = 0;
    //拷贝出所有的成员变量的列表
    Ivar *ivars =class_copyIvarList([Person class], &count);
    for (int i =0; i<count; i++) {
        //取出成员变量
        Ivar var = *(ivars + i);
        //打印成员变量名字
        NSLog(@"%s",ivar_getName(var));
    }
    //释放
    free(ivars);

通过打印

2018-07-18 14:53:31.388020+0800 property[65565:6257229] myName
2018-07-18 14:53:31.388183+0800 property[65565:6257229] _age

我们可以看出如果指定了实例变量名称,则会生成指定名称,不生成下划线的实例变量

  • 手动添加一个实例变量_name,查看属性name,是否会再次生成_name实例变量。
@interface Person() {
    NSString *_name;
}

打印结果

2018-07-18 15:04:00.529921+0800 property[65981:6265261] _name
2018-07-18 15:04:00.530097+0800 property[65981:6265261] _age

说明如果这个实例变量已经存在了就不再生成了。

  • @synthesize name;不指定实例变量名称
@interface Person : NSObject<NSCopying>
 // 姓名
@property (nonatomic, strong) NSString *name;
 // 年龄
@property (nonatomic, assign) NSInteger age;

/**
 初始化

 @param name 姓名
 @param age 年龄
 @return <#return value description#>
 */
- (instancetype)initWithName:(NSString *)name age:(NSInteger)age;

@end
@implementation Person

@synthesize name;

- (instancetype)initWithName:(NSString *)name age:(NSInteger)age {
    if (self = [super init]) {
        self.name = name;
        self.age = age;
    }
    return self;
}

- (id)copyWithZone:(NSZone *)zone {
    Person *person = [[self copyWithZone:zone] initWithName:self.name age:self.age];
    return person;
}

@end

打印出来为

2018-07-18 15:26:44.469981+0800 property[66020:6280688] name
2018-07-18 15:26:44.470200+0800 property[66020:6280688] _age

可以看出,@synthesize name;方式不指定实例变量名称,默认生成name实例变量,不生成_name。

  • 所以这个问题可以回答
  1. 如果通过@synthesize name = myName;。指定了生成指定的实例变量名称,则不生成_name实例变量,生成指定的实例变量。
  2. 如果@synthesize name;不知道实例变量名称,默认生成name实例变量,不生成_name。
    3 如果不写@synthesize ,默认生成_name实例变量
    4 如果已经存在_name实例变量,则不会重复生成_name实例变量
@property 的本质是什么?ivar、getter、setter 是如何生成并添加到这个类中的
  • 属性的本质就是ivar + getter + setter
  • 如果属性是默认@synthesize自动合成的,会默认自动生成setter和getter方法。并生成一个下划线的实例变量。
  • 如果属性的主动@synthesize声明的,会自动生成setter和getter方法,我们可以指定实例变量的变量名
  • 如果属性声明为dynamic,则需要我们手动生成setter和getter方法。
@protocol 和 category 中如何使用 @property

结论1: 在protocol中使用property只会生成setter和getter方法声明,我们使用属性的目的,是希望遵守我协议的对象能实现该属性

  • 我们开始测试
    新建一个hitView视图,里面有个身高属性
#import <UIKit/UIKit.h>

@protocol TestDetegate <NSObject>

// 身高属性
@property (nonatomic, assign) NSInteger height;
// 买票方法
- (void)mustBuyTicket;

@end

@interface HitView : UIView
 // 代理协议 
@property (nonatomic, weak) id<TestDetegate> testDetegate;

@end
#import "HitView.h"

@implementation HitView

 // 初始化
- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        self.backgroundColor = [UIColor redColor];
        [self addGes];
    }
    return self;
}

#pragma mark --- 添加点击手势
- (void)addGes {
    UITapGestureRecognizer *Tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(isCanBuyticket)];
    [self addGestureRecognizer:Tap];
}

- (void)isCanBuyticket {
    if ([self.testDetegate respondsToSelector:@selector(mustBuyTicket)]) {
        [self.testDetegate mustBuyTicket];
    }
}

@end

控制器中设置代理

@implementation ViewController
// 正常属性height无法使用,我们可以在遵循代理的对象中实现手动setter和getter
@synthesize height = _height;

- (void)viewDidLoad {
    [super viewDidLoad];
    
    HitView *hitView = [[HitView alloc] initWithFrame:CGRectMake(50, 50, 100, 100)];
    hitView.testDetegate = self;
    [self.view addSubview:hitView];
}

#pragma mark --- TestDetegate
- (void)mustBuyTicket {

    self.height = random() % 80 + 80;
    if (self.height > 120) {
        NSLog(@"当前高度为%ld,超过120,需要买票",(long)_height);
    } else {
        NSLog(@"当前高度为%ld,低于120,不需要买票",(long)_height);
    }
}

#pragma mark --- setter getter
- (NSInteger)height {
    return _height;
}

- (void)setHeight:(NSInteger)height {
    _height = height;
}

结论2: category 使用 @property 也是只会生成setter和getter方法的声明,如果我们真的需要给category增加属性的实现,需要借助于运行时的两个函数:

①objc_setAssociatedObject

②objc_getAssociatedObject
使用举例(button添加)额外的点击区域

- (CGFloat)addLength {
    return [objc_getAssociatedObject(self, @selector(addLength)) floatValue] ? [objc_getAssociatedObject(self, @selector(addLength)) floatValue] : 0;
}

- (void)setAddLength:(CGFloat)addLength {
    objc_setAssociatedObject(self, @selector(addLength), [NSNumber numberWithFloat:addLength], OBJC_ASSOCIATION_ASSIGN);
}

 // 重写按钮的点击区域
- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event {
    CGRect rect = CGRectInset(self.bounds, -self.addLength, -self.addLength);
    return CGRectContainsPoint(rect, point);
}
点击区域.gif

为什么分类中不能添加属性

我们知道在main函数之前OC类会被注册加入注册表,我们在main函数里打印UIScrollView类的子类

#import <UIKit/UIKit.h>
#import "AppDelegate.h"

#import <objc/runtime.h>

int main(int argc, char * argv[]) {    
    unsigned int outCount;
    Class *classes = objc_copyClassList(&outCount);
    for (int i = 0; i < outCount; i++) {
        @autoreleasepool {
            if (class_getSuperclass(classes[i]) == [UIScrollView class]) {
                NSLog(@"%s",class_getName(classes[i]));
            }
        }
    }
    free(classes);
    
    
    @autoreleasepool {
        return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
    }
}

打印结果

2018-08-15 15:43:09.173307+0800 runtime[14305:582281] _MKPlacePhotoView
2018-08-15 15:43:09.174570+0800 runtime[14305:582281] NUIContentScrollView
2018-08-15 15:43:09.174938+0800 runtime[14305:582281] _UIInterfaceActionRepresentationsSequenceView
2018-08-15 15:43:09.175165+0800 runtime[14305:582281] _UIQueuingScrollView
2018-08-15 15:43:09.175497+0800 runtime[14305:582281] _UIAlertControllerShadowedScrollView
2018-08-15 15:43:09.175687+0800 runtime[14305:582281] _UICompatibilityTextView
2018-08-15 15:43:09.175932+0800 runtime[14305:582281] UIPrinterSetupPINScrollView
2018-08-15 15:43:09.176088+0800 runtime[14305:582281] UITextView
2018-08-15 15:43:09.176227+0800 runtime[14305:582281] UIWebOverflowScrollView
2018-08-15 15:43:09.176600+0800 runtime[14305:582281] UIPageControllerScrollView
2018-08-15 15:43:09.176825+0800 runtime[14305:582281] UIWebScrollView
2018-08-15 15:43:09.177134+0800 runtime[14305:582281] UIFieldEditor
2018-08-15 15:43:09.177394+0800 runtime[14305:582281] UITableView
2018-08-15 15:43:09.177589+0800 runtime[14305:582281] UITableViewWrapperView
2018-08-15 15:43:09.177862+0800 runtime[14305:582281] UICollectionView

可以看出这些都是在main函数之前创建在注册表中类。

  • 我们通过runtime创建一个UIScrollView的子类runtimeScrollView,并添加实例变量
int main(int argc, char * argv[]) {
    
    // 创建一个类newClass继承Person
    Class newClass =  objc_allocateClassPair([UIScrollView class], "runtimeScrollView", 0);
    // 添加实例变量_skinColor
    BOOL flag1 = class_addIvar(newClass, "_skinColor", sizeof(NSString*), log2(sizeof(NSString *)), @encode(NSString *));
    if (flag1) {
        NSLog(@"NSString*类型  _skinColor变量添加成功");
    } else {
        NSLog(@"实例变量添加失败");
    }
    // 注册这个类
    objc_registerClassPair(newClass);
    
    unsigned int outCount;
    Class *classes = objc_copyClassList(&outCount);
    for (int i = 0; i < outCount; i++) {
        @autoreleasepool {
            if (class_getSuperclass(classes[i]) == [UIScrollView class]) {
                NSLog(@"%s",class_getName(classes[i]));
            }
        }
    }
    free(classes);
    
    
    @autoreleasepool {
        return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
    }
}

打印结果我们发现_skinColor实例变量添加成功,runtimeScrollView也被加入了注册表。

2018-08-15 15:52:44.350938+0800 runtime[14377:589744] NSString*类型  _skinColor变量添加成功
2018-08-15 15:52:44.433355+0800 runtime[14377:589744] _MKPlacePhotoView
2018-08-15 15:52:44.433711+0800 runtime[14377:589744] NUIContentScrollView
2018-08-15 15:52:44.434095+0800 runtime[14377:589744] _UIInterfaceActionRepresentationsSequenceView
2018-08-15 15:52:44.434343+0800 runtime[14377:589744] _UIQueuingScrollView
2018-08-15 15:52:44.434772+0800 runtime[14377:589744] _UIAlertControllerShadowedScrollView
2018-08-15 15:52:44.434942+0800 runtime[14377:589744] _UICompatibilityTextView
2018-08-15 15:52:44.435259+0800 runtime[14377:589744] runtimeScrollView
2018-08-15 15:52:44.435503+0800 runtime[14377:589744] UIPrinterSetupPINScrollView
2018-08-15 15:52:44.435623+0800 runtime[14377:589744] UITextView
2018-08-15 15:52:44.435772+0800 runtime[14377:589744] UIWebOverflowScrollView
2018-08-15 15:52:44.436187+0800 runtime[14377:589744] UIPageControllerScrollView
2018-08-15 15:52:44.436336+0800 runtime[14377:589744] UIWebScrollView
2018-08-15 15:52:44.436434+0800 runtime[14377:589744] UIFieldEditor
2018-08-15 15:52:44.436536+0800 runtime[14377:589744] UITableView
2018-08-15 15:52:44.436969+0800 runtime[14377:589744] UITableViewWrapperView
2018-08-15 15:52:44.437741+0800 runtime[14377:589744] UICollectionView
  • 现在把实例变量的创建放在注册之后,意思是在类注册完毕后,在添加实例变量
int main(int argc, char * argv[]) {
    
    // 创建一个类newClass继承Person
    Class newClass =  objc_allocateClassPair([UIScrollView class], "runtimeScrollView", 0);
    // 注册这个类
    objc_registerClassPair(newClass);
    
    unsigned int outCount;
    Class *classes = objc_copyClassList(&outCount);
    for (int i = 0; i < outCount; i++) {
        @autoreleasepool {
            if (class_getSuperclass(classes[i]) == [UIScrollView class]) {
                NSLog(@"%s",class_getName(classes[i]));
            }
        }
    }
    free(classes);
    
    // 添加实例变量_skinColor,注册后在新值实例变量
    BOOL flag1 = class_addIvar(newClass, "_skinColor", sizeof(NSString*), log2(sizeof(NSString *)), @encode(NSString *));
    if (flag1) {
        NSLog(@"NSString*类型  _skinColor变量添加成功");
    } else {
        NSLog(@"实例变量添加失败");
    }
    
    @autoreleasepool {
        return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
    }
}
  • 打印发现类runtimeScrollView新建成功,但是无法向类中添加实例变量了。
2018-08-15 15:53:46.992111+0800 runtime[14390:590687] _MKPlacePhotoView
2018-08-15 15:53:46.994071+0800 runtime[14390:590687] NUIContentScrollView
2018-08-15 15:53:46.994775+0800 runtime[14390:590687] _UIInterfaceActionRepresentationsSequenceView
2018-08-15 15:53:46.995204+0800 runtime[14390:590687] _UIQueuingScrollView
2018-08-15 15:53:46.995932+0800 runtime[14390:590687] _UIAlertControllerShadowedScrollView
2018-08-15 15:53:46.996475+0800 runtime[14390:590687] _UICompatibilityTextView
2018-08-15 15:53:46.997059+0800 runtime[14390:590687] runtimeScrollView
2018-08-15 15:53:46.997589+0800 runtime[14390:590687] UIPrinterSetupPINScrollView
2018-08-15 15:53:46.998016+0800 runtime[14390:590687] UITextView
2018-08-15 15:53:46.998161+0800 runtime[14390:590687] UIWebOverflowScrollView
2018-08-15 15:53:46.998562+0800 runtime[14390:590687] UIPageControllerScrollView
2018-08-15 15:53:46.998781+0800 runtime[14390:590687] UIWebScrollView
2018-08-15 15:53:46.999075+0800 runtime[14390:590687] UIFieldEditor
2018-08-15 15:53:46.999508+0800 runtime[14390:590687] UITableView
2018-08-15 15:53:46.999727+0800 runtime[14390:590687] UITableViewWrapperView
2018-08-15 15:53:47.000028+0800 runtime[14390:590687] UICollectionView
2018-08-15 15:53:47.000541+0800 runtime[14390:590687] 实例变量添加失败
  • 如果我们向一个注册过的类中添加方法,可以发现是已经添加成功的。
 Method method = class_getInstanceMethod([UIScrollView class], @selector(buyClothes));
    // 为类添加一个方法
   BOOL isSuccess =  class_addMethod([UIScrollView class], method_getName(method), method_getImplementation(method), method_getTypeEncoding(method));
    if (isSuccess) {
        NSLog(@"添加方法成功");
    } else {
        NSLog(@"添加方法失败");
    }
总结(在一个类被注册之后,我们无法在向类中动态class_addIvar添加实例变量)

所以我们可以知道在注册后的类中添加实例变量是不会成功,原因其实是因为注册过的类,类中的实例变量内存大小和数据结构就已经被确定,runtime 会调用 class_setIvarLayout 或 class_setWeakIvarLayout来确定每个实例对象的内存管理语义,weak,strong或者是其他的。

回到类别

1. 明白一个概念:属性是可以添加的。只是说现在Xcode自动会给属性生成成员变量让大家对这个概念有点混淆。Property是Property,Ivar是Ivar。类别可以添加属性,但是添加的只是属性的声明,意思就是不会自动合成,不会使用@synthesize关键词,Property是通过@synthesize关键词来标识自动生成Ivar,Getter,Setter的。
2. 我们通过runtime源码来查看分类category_t的定义,(在objc-runtime-new.h中可以找到此定义),目前runtime版本objc4-723

struct category_t {
    const char *name; // 类的名字
    classref_t cls; //类
    struct method_list_t *instanceMethods; //实例方法列表
    struct method_list_t *classMethods; //类方法列表
    struct protocol_list_t *protocols; // 协议列表
    struct property_list_t *instanceProperties; //实例方法列表
    // Fields below this point are not always present on disk.
    struct property_list_t *_classProperties; // 属性列表
 
    method_list_t *methodsForMeta(bool isMeta) {
        if (isMeta) return classMethods;
        else return instanceMethods;
    }

    property_list_t *propertiesForMeta(bool isMeta, struct header_info *hi);
};

可以看出分类结构体中我们就可以看出列表可以做的事情,(可以添加实例方法,类方法,实现协议,添加属性),但是无法添加实例变量。因为在运行期,对象的内存布局已经确定,如果添加实例变量就会破坏类的内部布局,这对编译型语言来说是灾难性的。
3 想深入分类查看原理的可以看美团团队写的深入理解Objective-C:Category

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 160,165评论 4 364
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,720评论 1 298
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,849评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,245评论 0 213
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,596评论 3 288
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,747评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,977评论 2 315
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,708评论 0 204
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,448评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,657评论 2 249
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,141评论 1 261
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,493评论 3 258
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,153评论 3 238
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,108评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,890评论 0 198
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,799评论 2 277
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,685评论 2 272

推荐阅读更多精彩内容