-
Notifications
You must be signed in to change notification settings - Fork 284
/
Copy pathNSKVOSwizzling.m
695 lines (612 loc) · 23.7 KB
/
NSKVOSwizzling.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
/**
NSKVOSwizzling.m
Copyright (C) 2024 Free Software Foundation, Inc.
Written by: Hugo Melder <hugo@algoriddim.com>
Date: June 2024
Based on WinObjC KVO tests by Microsoft Corporation.
This file is part of GNUStep-base
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
If you are interested in a warranty or support for this source code,
contact Scott Christley <scottc@net-community.com> for more information.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110 USA.
*/
/**
Copyright (c) Microsoft. All rights reserved.
This code is licensed under the MIT License (MIT).
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
/* This Key Value Observing Implementation is tied to libobjc2 */
#import "common.h"
#import "NSKVOInternal.h"
#import <objc/encoding.h>
#import <objc/runtime.h>
#import "NSKVOTypeEncodingCases.h"
#import <Foundation/Foundation.h>
#ifdef WIN32
#define alloca(x) _alloca(x)
#endif
/* These are defined by the ABI and the runtime. */
#define ABI_SUPER(obj) (((Class **) obj)[0][1])
#define ABI_ISA(obj) (((Class *) obj)[0])
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-objc-pointer-introspection"
// Small objects, as defined by libobjc2, are tagged pointers. Instead of being
// heap-allocated, the object is stored in the sizeof(id) -
// OBJC_SMALL_OBJECT_BITS bits of the "pointer" itself.
static inline bool
isSmallObject_np(id object)
{
return ((((uintptr_t) object) & OBJC_SMALL_OBJECT_MASK) != 0);
}
#pragma clang diagnostic pop
static void
NSKVO$setObject$forKey$(id self, SEL _cmd, id object, NSString *key);
static void
NSKVO$removeObjectForKey$(id self, SEL _cmd, NSString *key);
static void
NSKVO$nilIMP(id self, SEL _cmd)
{}
static void
_NSKVOEnsureObjectIsKVOAware(id object)
{
// We have to use ABI_ISA here, because object_getClass will skip the secret
// hidden subclass.
if (class_respondsToSelector(ABI_ISA(object), @selector(_isKVOAware)))
{
// The presence of _isKVOAware signals that we have already mangled this
// object.
return;
}
/*
A crucial design decision was made here: because object_getClass() skips
autogenerated subclasses, the likes of which are used for associated objects,
the KVO machinery (if implemented using manual subclassing) would delete all
associated objects on an observed instance. That was deemed unacceptable.
Likewise, this implementation is not free of issues:
- The _np methods are nonportable.
- Anyone using class_getMethodImplementation(object_getClass(...), ...) will
receive the original IMP for any overridden method.
- We have to manually load isa to get at the secret subclass (thus the use of
ABI_ISA/ABI_SUPER.)
- It is dependent upon a libobjc2 implementation detail:
object_addMethod_np creates a hidden subclass for the object's class (one
per object!)
*/
object_addMethod_np(object, @selector(setObject:forKey:),
(IMP)(NSKVO$setObject$forKey$), "v@:@@");
object_addMethod_np(object, @selector(removeObjectForKey:),
(IMP)(NSKVO$removeObjectForKey$), "v@:@");
object_addMethod_np(object, @selector(_isKVOAware),
(IMP)(NSKVO$nilIMP), "v@:");
}
#pragma region Method Implementations
// Selector mappings: the class-level mapping from a selector (setX:) to the KVC
// key ("x") to which it corresponds. This is necessary because both "X" and "x"
// map to setX:, but we need to be cognizant of precisely which it was for any
// given observee. The sole reason we can get away with keeping selector<->key
// mappings on the class is that, through the lifetime of said class, it can
// never lose selectors. This mapping will be pertinent to every instance of the
// class.
static inline NSMapTable *
_selectorMappingsForObject(id object)
{
static char s_selMapKey;
Class cls;
// here we explicitly want the public
// (non-hidden) class associated with the object.
cls = object_getClass(object);
@synchronized(cls)
{
NSMapTable *selMappings
= (NSMapTable *) objc_getAssociatedObject(cls, &s_selMapKey);
if (!selMappings)
{
selMappings = [NSMapTable
mapTableWithKeyOptions: NSPointerFunctionsOpaqueMemory
| NSPointerFunctionsOpaquePersonality
valueOptions: NSPointerFunctionsStrongMemory
| NSPointerFunctionsObjectPersonality];
objc_setAssociatedObject(cls, &s_selMapKey, (id) selMappings,
OBJC_ASSOCIATION_RETAIN);
}
return selMappings;
}
}
static inline NSString *
_keyForSelector(id object, SEL selector)
{
return (NSString *) NSMapGet(_selectorMappingsForObject(object),
sel_getName(selector));
}
static inline void
_associateSelectorWithKey(id object, SEL selector, NSString *key)
{
/* this must be insertIfAbsent. otherwise, when calling a setter that itself
* causes observers to be added/removed on this key, this would call this
* method and overwrite the association selector->key with an identical key
* but another object. unfortunately, this would mean that the
* notifyingSetImpl below would then have a dead ```key``` pointer once it
* came time to call didChangeValueForKey (because apparently ARC doesn't take
* care of this properly)
*/
NSMapInsertIfAbsent(_selectorMappingsForObject(object),
sel_getName(selector), key);
}
static void
notifyingVariadicSetImpl(id self, SEL _cmd, ...)
{
NSString *key = _keyForSelector(self, _cmd);
/* [Source: NSInvocation.mm]
* This attempts to flatten the method's arguments (as determined by its type
* encoding) from the stack into a buffer. That buffer is then emitted back
* onto the stack for the imp callthrough. This only works if we assume that
* our calling convention passes variadics and non-variadics in the same way:
* on the stack. For our two supported platforms, this seems to hold true.
*/
NSMethodSignature *sig = [self methodSignatureForSelector: _cmd];
size_t argSz = objc_sizeof_type([sig getArgumentTypeAtIndex: 2]);
size_t nStackArgs = argSz / sizeof(uintptr_t);
uintptr_t *raw = (uintptr_t *) (calloc(sizeof(uintptr_t), nStackArgs));
va_list ap;
va_start(ap, _cmd);
for (uintptr_t i = 0; i < nStackArgs; ++i)
{
raw[i] = va_arg(ap, uintptr_t);
}
va_end(ap);
[self willChangeValueForKey: key];
{
struct objc_super super = {self, ABI_SUPER(self)};
IMP imp = (id(*)(id, SEL, ...)) objc_msg_lookup_super(&super, _cmd);
// VSO 5955259; NSInvocation informs this implementation and this will need
// to be cleaned up when NSInvocation is.
switch (nStackArgs)
{
case 1:
imp(self, _cmd, raw[0]);
break;
case 2:
imp(self, _cmd, raw[0], raw[1]);
break;
case 3:
imp(self, _cmd, raw[0], raw[1], raw[2]);
break;
case 4:
imp(self, _cmd, raw[0], raw[1], raw[2], raw[3]);
break;
case 5:
imp(self, _cmd, raw[0], raw[1], raw[2], raw[3], raw[4]);
break;
case 6:
imp(self, _cmd, raw[0], raw[1], raw[2], raw[3], raw[4], raw[5]);
break;
default:
NSLog(@"Can't override setter with more than 6"
@" sizeof(long int) stack arguments.");
return;
}
}
[self didChangeValueForKey: key];
free(raw);
}
typedef void (*insertObjectAtIndexIMP)(id, SEL, id, NSUInteger);
typedef void (*removeObjectAtIndexIMP)(id, SEL, NSUInteger);
typedef void (*insertAtIndexesIMP)(id, SEL, id, NSIndexSet *);
typedef void (*removeAtIndexesIMP)(id, SEL, NSIndexSet *);
typedef void (*replaceAtIndexesIMP)(id, SEL, NSIndexSet *, NSArray *);
typedef void (*setObjectForKeyIMP)(id, SEL, id, NSString *);
typedef void (*removeObjectForKeyIMP)(id, SEL, NSString *);
typedef void (*replaceObjectAtIndexWithObjectIMP)(id, SEL, NSUInteger, id);
static void
NSKVONotifying$insertObject$inXxxAtIndex$(id self, SEL _cmd, id object,
NSUInteger index)
{
NSString *key = _keyForSelector(self, _cmd);
NSIndexSet *indexes = [NSIndexSet indexSetWithIndex: index];
[self willChange: NSKeyValueChangeInsertion
valuesAtIndexes: indexes
forKey: key];
{
struct objc_super super = {self, ABI_SUPER(self)};
insertObjectAtIndexIMP imp = (void (*)(id, SEL, id, NSUInteger))
objc_msg_lookup_super(&super, _cmd);
imp(self, _cmd, object, index);
}
[self didChange: NSKeyValueChangeInsertion
valuesAtIndexes: indexes
forKey: key];
}
static void
NSKVONotifying$insertXxx$atIndexes$(id self, SEL _cmd, id object,
NSIndexSet *indexes)
{
NSString *key = _keyForSelector(self, _cmd);
[self willChange: NSKeyValueChangeInsertion
valuesAtIndexes: indexes
forKey: key];
{
struct objc_super super = {self, ABI_SUPER(self)};
insertAtIndexesIMP imp = (void (*)(id, SEL, id, NSIndexSet *))
objc_msg_lookup_super(&super, _cmd);
imp(self, _cmd, object, indexes);
}
[self didChange: NSKeyValueChangeInsertion
valuesAtIndexes: indexes
forKey: key];
}
static void
NSKVONotifying$removeObjectFromXxxAtIndex$(id self, SEL _cmd, NSUInteger index)
{
NSString *key = _keyForSelector(self, _cmd);
NSIndexSet *indexes = [NSIndexSet indexSetWithIndex: index];
[self willChange: NSKeyValueChangeRemoval
valuesAtIndexes: indexes
forKey: key];
{
struct objc_super super = {self, ABI_SUPER(self)};
removeObjectAtIndexIMP imp = (void (*)(id, SEL, NSUInteger))
objc_msg_lookup_super(&super, _cmd);
imp(self, _cmd, index);
}
[self didChange: NSKeyValueChangeRemoval
valuesAtIndexes: indexes
forKey: key];
}
static void
NSKVONotifying$removeXxxAtIndexes$(id self, SEL _cmd, NSIndexSet *indexes)
{
NSString *key = _keyForSelector(self, _cmd);
[self willChange: NSKeyValueChangeRemoval
valuesAtIndexes: indexes
forKey: key];
{
struct objc_super super = {self, ABI_SUPER(self)};
removeAtIndexesIMP imp = (void (*)(id, SEL, NSIndexSet *))
objc_msg_lookup_super(&super, _cmd);
imp(self, _cmd, indexes);
}
[self didChange: NSKeyValueChangeRemoval
valuesAtIndexes: indexes
forKey: key];
}
static void
NSKVONotifying$replaceObjectInXxxAtIndex$withObject$(id self, SEL _cmd,
NSUInteger index, id object)
{
NSString *key = _keyForSelector(self, _cmd);
NSIndexSet *indexes = [NSIndexSet indexSetWithIndex: index];
[self willChange: NSKeyValueChangeReplacement
valuesAtIndexes: indexes
forKey: key];
{
struct objc_super super = {self, ABI_SUPER(self)};
replaceObjectAtIndexWithObjectIMP imp = (void (*)(id, SEL, NSUInteger, id))
objc_msg_lookup_super(&super, _cmd);
imp(self, _cmd, index, object);
}
[self didChange: NSKeyValueChangeReplacement
valuesAtIndexes: indexes
forKey: key];
}
static void
NSKVONotifying$replaceXxxAtIndexes$withXxx$(id self, SEL _cmd,
NSIndexSet *indexes, NSArray *objects)
{
NSString *key = _keyForSelector(self, _cmd);
[self willChange: NSKeyValueChangeReplacement
valuesAtIndexes: indexes
forKey: key];
{
struct objc_super super = {self, ABI_SUPER(self)};
replaceAtIndexesIMP imp = (void (*)(id, SEL, NSIndexSet *, NSArray *))
objc_msg_lookup_super(&super, _cmd);
imp(self, _cmd, indexes, objects);
}
[self didChange: NSKeyValueChangeReplacement
valuesAtIndexes: indexes
forKey: key];
}
#define GENERATE_NSKVOSetDispatch_IMPL(Kind) \
static inline void _NSKVOSetDispatch_##Kind(id self, SEL _cmd, NSSet *set) \
{ \
NSString *key = _keyForSelector(self, _cmd); \
[self willChangeValueForKey: key withSetMutation: Kind usingObjects: set]; \
{ \
struct objc_super super = {self, ABI_SUPER(self)}; \
void (*imp)(id, SEL, NSSet *) \
= (void (*)(id, SEL, NSSet *)) objc_msg_lookup_super(&super, _cmd); \
imp(self, _cmd, set); \
} \
[self didChangeValueForKey: key withSetMutation: Kind usingObjects: set]; \
}
#define GENERATE_NSKVOSetDispatchIndividual_IMPL(Kind) \
static inline void _NSKVOSetDispatchIndividual_##Kind(id self, SEL _cmd, \
id obj) \
{ \
NSSet *set = [NSSet setWithObject: obj]; \
NSString *key = _keyForSelector(self, _cmd); \
[self willChangeValueForKey: key withSetMutation: Kind usingObjects: set]; \
{ \
struct objc_super super = {self, ABI_SUPER(self)}; \
void (*imp)(id, SEL, id) \
= (void (*)(id, SEL, id)) objc_msg_lookup_super(&super, _cmd); \
imp(self, _cmd, obj); \
} \
[self didChangeValueForKey: key withSetMutation: Kind usingObjects: set]; \
}
GENERATE_NSKVOSetDispatchIndividual_IMPL(NSKeyValueUnionSetMutation);
GENERATE_NSKVOSetDispatchIndividual_IMPL(NSKeyValueMinusSetMutation);
//GENERATE_NSKVOSetDispatchIndividual_IMPL(NSKeyValueIntersectSetMutation);
GENERATE_NSKVOSetDispatch_IMPL(NSKeyValueUnionSetMutation);
GENERATE_NSKVOSetDispatch_IMPL(NSKeyValueMinusSetMutation);
GENERATE_NSKVOSetDispatch_IMPL(NSKeyValueIntersectSetMutation);
// - (void)setObject: (id)object forKey: (NSString*)key
static void
NSKVO$setObject$forKey$(id self, SEL _cmd, id object, NSString *key)
{
[self willChangeValueForKey: key];
{
struct objc_super super = {self, ABI_SUPER(self)};
setObjectForKeyIMP imp;
imp = (void (*)(id, SEL, id, NSString *)) objc_msg_lookup_super(&super, _cmd);
imp(self, _cmd, object, key);
}
[self didChangeValueForKey: key];
}
// - (void)removeObjectForKey: (NSString*)key
static void
NSKVO$removeObjectForKey$(id self, SEL _cmd, NSString *key)
{
[self willChangeValueForKey: key];
{
struct objc_super super = {self, ABI_SUPER(self)};
removeObjectForKeyIMP imp;
imp = (void (*)(id, SEL, NSString *)) objc_msg_lookup_super(&super, _cmd);
imp(self, _cmd, key);
}
[self didChangeValueForKey: key];
}
#pragma endregion
#define GENERATE_NOTIFYING_SET_IMPL(funcName, type) \
static void funcName(id self, SEL _cmd, type val) \
{ \
struct objc_super super = {self, ABI_SUPER(self)}; \
NSString *key = _keyForSelector(self, _cmd); \
void (*imp)(id, SEL, type) \
= (void (*)(id, SEL, type)) objc_msg_lookup_super(&super, _cmd); \
[self willChangeValueForKey: key]; \
imp(self, _cmd, val); \
[self didChangeValueForKey: key]; \
}
GENERATE_NOTIFYING_SET_IMPL(notifyingSetImplDouble, double);
GENERATE_NOTIFYING_SET_IMPL(notifyingSetImplFloat, float);
GENERATE_NOTIFYING_SET_IMPL(notifyingSetImplChar, signed char);
GENERATE_NOTIFYING_SET_IMPL(notifyingSetImplInt, int);
GENERATE_NOTIFYING_SET_IMPL(notifyingSetImplShort, short);
GENERATE_NOTIFYING_SET_IMPL(notifyingSetImplLong, long);
GENERATE_NOTIFYING_SET_IMPL(notifyingSetImplLongLong, long long);
GENERATE_NOTIFYING_SET_IMPL(notifyingSetImplUnsignedChar, unsigned char);
GENERATE_NOTIFYING_SET_IMPL(notifyingSetImplUnsignedInt, unsigned int);
GENERATE_NOTIFYING_SET_IMPL(notifyingSetImplUnsignedShort, unsigned short);
GENERATE_NOTIFYING_SET_IMPL(notifyingSetImplUnsignedLong, unsigned long);
GENERATE_NOTIFYING_SET_IMPL(notifyingSetImplUnsignedLongLong,
unsigned long long);
// GENERATE_NOTIFYING_SET_IMPL(notifyingSetImplBool, bool);
GENERATE_NOTIFYING_SET_IMPL(notifyingSetImplObject, id);
GENERATE_NOTIFYING_SET_IMPL(notifyingSetImplPointer, void *);
#define KVO_SET_IMPL_CASE(type, name, capitalizedName, encodingChar) \
case encodingChar: { \
newImpl = (IMP) (¬ifyingSetImpl##capitalizedName); \
break; \
}
SEL
KVCSetterForPropertyName(NSObject *self, const char *key)
{
SEL sel = nil;
size_t len = strlen(key);
// For the key "example", we must construct the following buffer:
// _ _ _ _ x a m p l e _ \0
// and fill it with the following characters:
// s e t E x a m p l e : \0
char *buf = (char *) alloca(3 + len + 2);
memcpy(buf + 4, key + 1, len);
buf[0] = 's';
buf[1] = 'e';
buf[2] = 't';
buf[3] = toupper(key[0]);
buf[3 + len] = ':';
buf[3 + len + 1] = '\0';
sel = sel_getUid(buf);
if ([self respondsToSelector: sel])
{
return sel;
}
return nil;
}
// invariant: rawKey has already been capitalized
static inline void
_NSKVOEnsureSimpleKeyWillNotify(id object, NSString *key, const char *rawKey)
{
Method originalMethod;
const char *valueType;
const char *types;
NSMethodSignature *sig;
SEL sel;
IMP newImpl = NULL;
sel = KVCSetterForPropertyName(object, rawKey);
originalMethod = class_getInstanceMethod(object_getClass(object), sel);
types = method_getTypeEncoding(originalMethod);
if (!types)
{
return;
}
sig = [NSMethodSignature signatureWithObjCTypes: types];
valueType = [sig getArgumentTypeAtIndex: 2];
switch (valueType[0])
{
OBJC_APPLY_ALL_TYPE_ENCODINGS(KVO_SET_IMPL_CASE);
case '{':
case '[': {
size_t valueSize = objc_sizeof_type(valueType);
if (valueSize > 6 * sizeof(uintptr_t))
{
[NSException raise: NSInvalidArgumentException
format: @"Class %s key %@ has a value size of %u bytes"
@", and cannot currently be KVO compliant.",
class_getName(object_getClass(object)), key,
(unsigned int) (valueSize)];
}
newImpl = (IMP) (¬ifyingVariadicSetImpl);
break;
}
default:
[NSException raise: NSInvalidArgumentException
format: @"Class %s is not KVO compliant for key %@.",
class_getName(object_getClass(object)), key];
return;
}
_associateSelectorWithKey(object, sel, key);
object_addMethod_np(object, sel, newImpl, types);
}
static void
replaceAndAssociateWithKey(id object, SEL sel, NSString *key, IMP imp)
{
if ([object respondsToSelector: sel])
{
const char *selName = sel_getName(sel);
Method method = class_getInstanceMethod(object_getClass(object), sel);
if (!method)
{
NSWarnLog(@"NSObject (NSKeyValueObservation): Unable to find method "
@"for %s on class %s; perhaps it is a forward?",
selName, object_getClassName(object));
return;
}
_associateSelectorWithKey(object, sel, key);
object_replaceMethod_np(object, sel, imp, method_getTypeEncoding(method));
}
}
static SEL
formatSelector(NSString *format, ...)
{
NSString *s;
SEL sel;
va_list ap;
va_start(ap, format);
s = [[NSString alloc] initWithFormat: format arguments: ap];
sel = NSSelectorFromString([s autorelease]);
va_end(ap);
return sel;
}
// invariant: rawKey has already been capitalized
static inline void
_NSKVOEnsureOrderedCollectionWillNotify(id object, NSString *key,
const char *rawKey)
{
SEL insertOne = formatSelector(@"insertObject:in%sAtIndex:", rawKey);
SEL insertMany = formatSelector(@"insert%s:atIndexes:", rawKey);
if ([object respondsToSelector: insertOne]
|| [object respondsToSelector: insertMany])
{
replaceAndAssociateWithKey(object, insertOne, key,
(IMP)NSKVONotifying$insertObject$inXxxAtIndex$);
replaceAndAssociateWithKey(object, insertMany, key,
(IMP)NSKVONotifying$insertXxx$atIndexes$);
replaceAndAssociateWithKey(
object, formatSelector(@"removeObjectFrom%sAtIndex:", rawKey), key,
(IMP)NSKVONotifying$removeObjectFromXxxAtIndex$);
replaceAndAssociateWithKey(object,
formatSelector(@"remove%sAtIndexes:", rawKey),
key, (IMP)NSKVONotifying$removeXxxAtIndexes$);
replaceAndAssociateWithKey(
object, formatSelector(@"replaceObjectIn%sAtIndex:withObject:", rawKey),
key, (IMP)NSKVONotifying$replaceObjectInXxxAtIndex$withObject$);
replaceAndAssociateWithKey(
object, formatSelector(@"replace%sAtIndexes:with%s:", rawKey, rawKey),
key, (IMP)NSKVONotifying$replaceXxxAtIndexes$withXxx$);
}
}
// invariant: rawKey has already been capitalized
static inline void
_NSKVOEnsureUnorderedCollectionWillNotify(id object, NSString *key,
const char *rawKey)
{
SEL addOne = formatSelector(@"add%sObject:", rawKey);
SEL addMany = formatSelector(@"add%s:", rawKey);
SEL removeOne = formatSelector(@"remove%sObject:", rawKey);
SEL removeMany = formatSelector(@"remove%s:", rawKey);
if (([object respondsToSelector: addOne]
|| [object respondsToSelector: addMany])
&& ([object respondsToSelector: removeOne]
|| [object respondsToSelector: removeMany]))
{
replaceAndAssociateWithKey(
object, addOne, key,
(IMP)_NSKVOSetDispatchIndividual_NSKeyValueUnionSetMutation);
replaceAndAssociateWithKey(
object, addMany, key,
(IMP)_NSKVOSetDispatch_NSKeyValueUnionSetMutation);
replaceAndAssociateWithKey(
object, removeOne, key,
(IMP)_NSKVOSetDispatchIndividual_NSKeyValueMinusSetMutation);
replaceAndAssociateWithKey(
object, removeMany, key,
(IMP)_NSKVOSetDispatch_NSKeyValueMinusSetMutation);
replaceAndAssociateWithKey(
object, formatSelector(@"intersect%s:", rawKey), key,
(IMP)_NSKVOSetDispatch_NSKeyValueIntersectSetMutation);
}
}
char *
mutableBufferFromString(NSString *string)
{
NSUInteger lengthInBytes = [string length] + 1;
char *rawKey = (char *) malloc(lengthInBytes);
[string getCString: rawKey
maxLength: lengthInBytes
encoding: NSASCIIStringEncoding];
return rawKey;
}
// NSKVOEnsureKeyWillNotify is the main entrypoint into the swizzling code.
void
_NSKVOEnsureKeyWillNotify(id object, NSString *key)
{
char *rawKey;
// Since we cannot replace the isa of tagged pointer objects, we can't swizzle
// them.
if (isSmallObject_np(object))
{
return;
}
// A class is allowed to decline automatic swizzling for any/all of its keys.
if (![[object class] automaticallyNotifiesObserversForKey: key])
{
return;
}
rawKey = mutableBufferFromString(key);
rawKey[0] = toupper(rawKey[0]);
@synchronized(object)
{
_NSKVOEnsureObjectIsKVOAware(object);
_NSKVOEnsureSimpleKeyWillNotify(object, key, rawKey);
_NSKVOEnsureOrderedCollectionWillNotify(object, key, rawKey);
_NSKVOEnsureUnorderedCollectionWillNotify(object, key, rawKey);
}
free(rawKey);
}