我们按照源码查找一路找到attachCategories方法,我们发现这个方法就是对分类的实现。里面第一句解释Attach method lists and properties and protocols from categories to a class.将方法列表、属性和协议从类别附加到类中。
2020-06-2715:41:13.085990+0800 KVC[2974:107108] *** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<Person 0x600000d90160> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key stu.height.' *** First throw call stack: ( 0 CoreFoundation 0x00007fff23c7127e __exceptionPreprocess + 350 1 libobjc.A.dylib 0x00007fff513fbb20 objc_exception_throw + 48 2 CoreFoundation 0x00007fff23c70e49 -[NSException raise] + 9
打印结果是this class is not key value coding-compliant for the key stu.height.,所以这个方法是不可以的,但是iOS为我们提供了另一个方法KeyPath:
2020-06-2312:17:41.812979+0800 KVO[28865:5328765] person1添加KVO监听之前 - Person Person 2020-06-2312:17:41.814729+0800 KVO[28865:5328765] person1添加KVO监听之后 - NSKVONotifying_Person Person
Traceback (most recent call last): File "/Users/kris/PycharmProjects/pythons_demo/Python语言及其应用/第七章/test.py", line 26, in <module> ds = name.encode('ascii') UnicodeEncodeError: 'ascii' codec can't encode character '\u4e2d' in position 0: ordinal not in range(128)
A little help here? Traceback (most recent call last): File "/Users/kris/PycharmProjects/pythons_demo/Python语言及其应用/对象和类/创建类.py", line 41, in <module> give_me_a_car.need_a_push() AttributeError: 'Car'object has no attribute 'need_a_push'
使用super()从父类获得帮助。子类中想要调用父类的方法需要使用super()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
classPerson(): def__init__(self, name): self.name = name
Automatic key-value observing is implemented using a technique called isa-swizzling.
The isa pointer, as the name suggests, points to the object’s class which maintains a dispatch table. This dispatch table essentially contains pointers to the methods the class implements, among other data.
When an observer is registered for an attribute of an object the isa pointer of the observed object is modified, pointing to an intermediate class rather than at the true class. As a result the value of the isa pointer does not necessarily reflect the actual class of the instance.
You should never rely on the isa pointer to determine class membership. Instead, you should use the class method to determine the class of an object instance. 大致意思是:KVO使用isa-swizzling技术实现,对象添加观察者之后,isa指针会指向一个临时的类,不能依赖isa的值来判断类的关系,应该使用class方法来判断实例对象真实的类。 接下来使用代码来验证KVO的执行过程: Person.h (Person.m中什么也没有)
2019-03-31 19:06:48.896565+0800 KVO测试Demo[29498:3594134] Person - setAge: age 2019-03-31 19:06:48.897033+0800 KVO测试Demo[29498:3594134] p1 class = Person 2019-03-31 19:06:48.897503+0800 KVO测试Demo[29498:3594134] NSKVONotifying_Person - setAge: class dealloc _isKVOA 2019-03-31 19:06:48.897638+0800 KVO测试Demo[29498:3594134] p1 class = Person