Jonathan.
Jonathan.

Reputation: 55554

performSelector:withObject:, but not with an object

I want to do performSelector:withObject: but where the object is a CGFloat. So it's not actually an object. How can I do this?

the object I am performing the selector on is not mine, I can't modify it.

eg

[xyz performSelector:@selector(setOffset:) withObject:2];

(after posting I changed what I need to slightly to this:

[xyz performSelector:@selector(setOffset:) withObject:CGSizeMake(2,0)];

Upvotes: 2

Views: 2102

Answers (5)

Joe Yang
Joe Yang

Reputation: 1645

try use IMP (A pointer to the start of a method implementation.)

SEL setOffsetSEL = @selector(setOffset:);
IMP setOffsetIMP = [XYZClass instanceMethodForSelector:setOffsetSEL];
setOffsetIMP(xyz, setOffsetSEL, 2);

Upvotes: 1

Luca Bernardi
Luca Bernardi

Reputation: 4199

You can use:

[NSNumber numberWithFloat:(float)value]

Upvotes: -3

Justin Spahr-Summers
Justin Spahr-Summers

Reputation: 16973

If you're trying to invoke an arbitrary selector against an object you don't have control over, you could use an NSInvocation to set up the selector, target, and arguments, and obtain the return value after the method has been executed.

Generally, though, there are simpler solutions.

Upvotes: 3

Shaggy Frog
Shaggy Frog

Reputation: 27601

object passed is a CGFloat. So it's not actually an object.

As you wrote immediately after, if you're passed an object, it can't be a CGFloat, as CGFloat is a typedef'ed primitive (float or double).

If you've been passed a number value as an object, likely you were passed an NSNumber somehow.

With zero context to your question, there's no way to be sure.

Upvotes: 0

bbum
bbum

Reputation: 162712

You need an object to message. When I've needed to do something like this, I'll create a simple container class, shove the data in an instance and then perform a selector (often @selector(doIt:)) when needed.

If you can target 4.x, you can use blocks for this, too, typically.

(Without knowing more about what exactly you are trying to do, hard to get any more specific.)

Upvotes: 0

Related Questions