开发者

Invoke selector with scalar argument

开发者 https://www.devze.com 2023-02-09 01:49 出处:网络
I currently use 开发者_C百科objc_msgSend to invoke such selector on collection of object. Is there any better way to do that? Here is my code:

I currently use 开发者_C百科objc_msgSend to invoke such selector on collection of object. Is there any better way to do that? Here is my code:

@protocol ADelegateProtocol {
   -(void) timeToEventOneDidChange:(NSInterval) event1;
   -(void) timeToEventTwoDidChange:(NSInterval) event1;
}

- (void) delegatesPerformSelector:(SEL) selector withTimeIntervalAsFristParameter:(NSTimeinterval) timeInterval {
    for (id<ADelegateProtocol> delegate in delegates) {
        if([delegate respondsToSelector:selector]) {
            objc_msgSend(delegate, selector, timeInterval);
        }
    }
}

The selector is passed in as a parameter, timeInterval is a non-object value.

Note: I don't want to use KVO.


If you are going to use objc_msgSend() you must create a correctly typecast function pointer to do so. Relying on varargs to map to non-varargs doesn't work in all cases.

I.e. You'd want:

void (*myMessage)(id, SEL, NSTimeInterval) = objc_msgSend;
myMessage(delegate, aSelector, aTimeInterval);

(typed into SO -- consider the syntax an approximation. :)


What you can use beside objc_msgSend (which of course works), is NSInvocation. Personally I prefer the objc_msgSend way as its the most overhead free way to do this. Its also the more faster way, but this shouldn't matter in a normal App (it does matter in games).

Well, the choice is yours, both ways work and there is nothing bad with objc_msgSend or NSInvocation (beside that C code looks wrong in an ObjC method).


If delegates is an NSArray: what about using NSArray's makeObjectsPerformSelector:(SEL)aSelector.
If you need to pass an object along as a parameter, you can use makeObjectsPerformSelector:(SEL)aSelector withObject:(id)anObject.

0

精彩评论

暂无评论...
验证码 换一张
取 消