[swift-dev] NSProxy dynamic casting to Swift or ObjC class behaves differently

Joe Groff jgroff at apple.com
Wed Jun 8 12:52:46 CDT 2016


> On Jun 8, 2016, at 12:44 AM, Yavuz Nuzumlalı via swift-dev <swift-dev at swift.org> wrote:
> 
> Hi all,
> 
> swift_dynamicCastClassUnconditional and swift_dynamicCastObjCClassUnconditional methods behave differently while verifying casting.
> 
> swift_dynamicCastObjCClassUnconditional method calls -isKindOfClass: method before falling back to object_getClass function.
> 
> swift_dynamicCastClassUnconditional method calls swift_dynamicCastClass method which calls _swift_getClassOfAllocated method which calls directly object_getClass function.
> 
> This causes problems if underlying object is an NSProxy subclass.
> 
> NSProxy class does not implement -isKindOfClass: method, so calls to this method are forwarded to the real object through -forwardInvocation: method, which causes -isKindOfClass: method to return answer according to the real object's class.
> 
> However, object_getClass function directly accesses to the metadata of the given object, so it returns NSProxy subclass.
> 
> I think this is a conflicting behavior, and I think swift_dynamicCastClassUnconditional method should also verify first using -isKindOfClass: method, in order to provide consistency.

This is intentional, since NSProxy instances are generally expected to be standins for the proxied object. Important Cocoa idioms break down if the "real" class is exposed instead of the class a proxy pretends to be.

-Joe


More information about the swift-dev mailing list