paulrehkugler
paulrehkugler

Reputation: 3271

Objective-C Block Parameter Type Inference

I saw the following paragraph in the documentation for -[NSItemProvider loadItemForTypeIdentifier:options:completionHandler:]:

An extension can specify an expected class for the item’s value in the completion handler block. An error is returned in the completion block’s error parameter if the returned item’s value class doesn’t match the specified class. An item provider can perform simple type conversions for the item specified in the block, such as from NSURL to NSData or NSFileWrapper, or from NSData to UIImage (in iOS) or NSImage (in OS X).

Not that I'd ever want to make an API as crazy as that, but now I'm curious. How does runtime block type inference work?

Upvotes: 0

Views: 317

Answers (2)

paulrehkugler
paulrehkugler

Reputation: 3271

Apparently this isn't new. It's already been answered here.

Basically, you can redeclare the private parts of the block ABI publicly (see this struct definition) and use that to create an NSMethodSignature (see this line of code).

Upvotes: 1

KirkSpaziani
KirkSpaziani

Reputation: 1972

from the docs:

typedef void (^NSItemProviderCompletionHandler)(id <NSSecureCoding> item, NSError *error);

Discussion: To complete a loading request, a block of this form is called to give you a chance to verify the item’s type and handle it appropriately.

So it appears the purpose of the block is to give the coder a way to step in and verify things.

There's a lot of ways to use the Objective-C runtime. The simplest way is to use the methods that the NSObject protocol defines (Not to be confused with the NSObject class...)

-(BOOL)isKindOfClass:(Class)aClass;
-(BOOL)isMemberOfClass:(Class)aClass;
-(BOOL)respondsToSelector:(SEL)aSel
-(BOOL)conformsToProtocol:(Protocol*)aProtocol;

Upvotes: 0

Related Questions