开发者

Create a SEL with an object passed into it

开发者 https://www.devze.com 2023-02-28 14:12 出处:网络
I know how to use: [self method:object]; But is it possible to get a SEL object of this? SEL method = @selector(开发者_如何学编程method:object);

I know how to use:

[self method:object];

But is it possible to get a SEL object of this?

SEL method = @selector(开发者_如何学编程method:object);

Doesn't work.

Thanks :)


A SEL is just the selector - the name of the message that's sent. To capture a specific instance of that message, its arguments, and its return value as an object, you need to use NSMethodSignature and NSInvocation. An example, based on your hypothetical -method:object above:

NSMethodSignature *sig = [SomeClass instanceMethodSignatureForSelector:@selector(method:)];
NSInvocation *inv = [NSInvocation invocationWithMethodSignature:sig];

// Assume that someObject is an instance of SomeClass
[inv setTarget:someObject];

// Assume an "id object" declared elsewhere.
// Also note that self & _cmd are at indices 0 & 1, respectively
[inv setArgument:&object atIndex:2]

// Some time later...
[inv invoke];

Note that, because an NSInvocation is an object, it doesn't have to be invoked immediately. It can be stored for later use, and usually is - there are far easier ways to send a message if one wants to do so immediately. Cocoa's standard undo/redo machinery, for example, is based on storing and invoking NSInvocations.


A @selector is something that is of another method or function.

Take this for an example:

-(IBAction)timerStart {
timer = [NSTimer scheduledTimerWithTimeInterval:2.0
target:self
selector:@selector(targetMethod:)
userInfo:nil
repeats:NO];
}

-(void)targetMethod:(id)sender {
[timer invalidate];
timer = nil;
}

As you can see, the selector (targetMethod:) is being called to action after two seconds of the NSTimer is run. The targetMethod: is a (void)function:(id)sender and therefore that is run.

In your case, what I think you're trying to accomplish is

[self performSelector:@selector(methodName:)];
0

精彩评论

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