Here is the example code I saw from Apple's "Timer Programming Topics":
NSMethodSignature *methodSignature = [self
methodSignatureForSelector:@selector(invocationMethod:)];
NSInvocation *invocation = [NSInvocation
invocationWithMethodSignature:methodSignature];
[invocation setTarget:self];
[invocation setSelector:@selector(invocationMethod:)];
NSDate *startDate = [NSDate date];
[invocation setArgument:&startDate atIndex:2];
as you can see, we have to specify the invocationMethod
: once in the NSMethodSignature
, and then second time in NSInvocation
's setSelector
.
To me, this seems redundant, is there any reason why Apple design like this?
A selector is just a string, the name of the method. It contains no information about the types of parameters or return type. A method signature is just the types; it contains no information about the name of the method. They are completely disjoint.
Although in your case you create the method signature by asking the target object using methodSignatureForSelector:
, you should not assume that people always want to do it that way.
You could construct a method signature directly from a string of type encodings. You could get it from the signature of another method and apply it to this method. Etc. It might not be appropriate, depending on the particular use case, to directly ask the object for the method signature, because maybe the object doesn't implement that method yet, and will dynamically add it later when called or something. There could be any of a number of reasons why it is useful to have the flexibility of specifying the types and method name separately.