objective C using a string to call a method - objective-c

Hi im new to objective C and was wondering if someone might be able to help me with this. I have a few different methods each requiring 3 input values and normally call it using
[self methodA:1 height:10 speed:3]
but the method name I want to read from a string in a plist so for example if the string was methodB i would get
[self methodB:1 height:10 speed:3]
for "methodC"
[self methodC:1 height:10 speed:3]
and so on.
Any ideas how I might do this I tried defining the string as a Selector using NSSelectorFromString
NSString *string = [plistA objectForKey:#"method"];
SEL select = NSSelectorFromString(string);
[self performSelector:select:c height:b speed:a];
However this did not work either any help would be greatly appreciated.
Have tried the solution below but could not get to work here is what i've tried.
So just to recap I have methods such as
spawnEnemyA:2 withHeight:3 withSpeed:4
spawnEnemyB:3 withHeight:2 withSpeed:5
and I want to read the values I want to pass to these methods as well as the method type from a plist file. my code is as follows, //////////////////////////////////////////////////////////////
//These are the values I read from the plist that I want my method to use
int a = [[enemySettings objectForKey:#"speed"] intValue];
int b = [[enemySettings objectForKey:#"position"] intValue];
int c = [[enemySettings objectForKey:#"delay"] intValue];
// I Also read the method name from the plist and combine it into a single string
NSString *method = [enemySettings objectForKey:#"enemytype"];
NSString *label1 = #"spawn";
NSString *label2 = #":withHeight:withSpeed:";
NSString *combined = [NSString stringWithFormat:#"%#%#%#",label1, method,label2];
//Check that the string is correct get spawnEnemyA:withHeight:withSpeed:
CCLOG(#"%#",combined);
//This is the Invocation part
NSInvocation * invocation = [ NSInvocation new ];
[ invocation setSelector: NSSelectorFromString(combined)];
[ invocation setArgument: &c atIndex: 2 ];
[ invocation setArgument: &b atIndex: 3 ];
[ invocation setArgument: &a atIndex: 4 ];
[ invocation invokeWithTarget:self ];
[invocation release ];
////////////////////////////////////////////////////////////////////
The code compiles without any errors but the methods are not called. Any ideas? Cheers

You can't use performSelector for a method with 3 (or more) arguments.
But for your information, here's how to use it:
SEL m1;
SEL m2;
SEL m3;
m1 = NSSelectorFromString( #"someMethodWithoutArg" );
m2 = NSSelectorFromString( #"someMethodWithAnArg:" );
m1 = NSSelectorFromString( #"someMethodWithAnArg:andAnotherOne:" );
[ someObject performSelector: m1 ];
[ someObject performSelector: m2 withObject: anArg ];
[ someObject performSelector: m2 withObject: anArg withObject: anOtherArg ];
For methods with more than 2 arguments, you will have to use the NSInvocation class.
Take a look at the documentation to learn how to use it.
Basically:
NSInvocation * invocation = [ NSInvocation new ];
[ invocation setSelector: NSStringFromSelector( #"methodWithArg1:arg2:arg3:" ) ];
// Argument 1 is at index 2, as there is self and _cmd before
[ invocation setArgument: &arg1 atIndex: 2 ];
[ invocation setArgument: &arg2 atIndex: 3 ];
[ invocation setArgument: &arg3 atIndex: 4 ];
[ invocation invokeWithTarget: targetObject ];
// If you need to get the return value
[ invocation getReturnValue: &someVar ];
[ invocation release ];

In general, this kind of dynamism often indicates an anti-pattern. Colluding data with implementation in this fashion is not generally a best practice.
Sometimes, though, it is necessary. If you are going down this path, then given that your various method declarations likely look like:
- (void)methodAWidth:(NSUInteger)w height:(NSUInteger)h speed:(NSUInteger)s;
- (void)methodBWidth:(NSUInteger)w height:(NSUInteger)h speed:(NSUInteger)s;
- (void)methodCWidth:(NSUInteger)w height:(NSUInteger)h speed:(NSUInteger)s;
You would probably want something like:
NSString *selName = [NSString stringWithFormat:#"method%#Width:height:speed:", ... one of #"A", #"B", or #"C" ....];
SEL selector = NSelectorFromString(selName);
Then:
if (![target respondsToSelector:selector])
return; // no can do
void (*castMsgSend)(id, SEL, NSUInteger, NSUInteger, NSUInteger) = (void*)objc_msgSend;
castMsgSend(target, selector, 1, 10, 3);
Every method call is compiled down to a call to objc_msgSend(). By doing the above, you are creating a fully type-safe/type-checked call site that goes through the normal Objective-C messaging mechanism, but the selector is dynamically defined on the fly.\
While performSelector: (and multi-arg variants) are handy, they can't deal with non-object types.
And, as MacMade pointed out in a comment, watch out for floating point and structure returns. They use different variants of objc_msgSend() that the compiler automatically handles in the normal [foo bar] case.

You can directly use objc_msgsend:
NSString *methodName = [plistA objectForKey:#"method"];
objc_msgSend(self, methodName, c, b, a);
Mind that the selector must include all pieces, eg #"method:height:speed:"

You should replace the following line with:
[self performSelector:select:c height:b speed:a];
and write following:
[self performSelector:select withObject:[NSArray arrayWithObjects:c,b,a,nil]];

Related

Objective C - Passing a float through a selector

I'm trying to pass a float through a selector using 'withObject:' however, it only accepts objects.
There are solutions that tell me to use [NSNumber numberWithFloat: ] however it's messing with the value of my float. I am doing a before and after testing of the values of the float, and beforehand I get numbers such as 0.0034324, whereas afterwards they are all 0.0000000
[[self gameObjects] makeObjectsPerformSelector:#selector(update:) withObject: <what to put here>]];
Thanks in advance!
EDIT*
here is the context
-(void) tick:(float)dt{
NSLog(#"%f",dt)
[[self gameObjects] makeObjectsPerformSelector:#selector(update:) withObject:[NSNumber numberWithFloat:dt]];
}
The number outputted from above is NOT 0
But from the selector method....
- (void)update:(float)dt{
NSLog(#"%f",dt);
}
The output is 0
You should wrap the float in an NSNumber.
NSNumber * num = [NSNumber numberWithFloat:5.5];
EDIT:
As rmaddy has pointed out, here are some other ways to use NSNumber *
NSNumber * num = #5.5f;
float someFloat = 5.5f;
NSNumber * num1 = #(someFloat);
To OP,
We need to see more of your code to help dissect the actual problem
Update to respond to new context
In your target method you are specifying that you expect a (float) as the expected argument. It is important to be cognizant of the type of variable you are passing to functions. Notice the last argument to your makeObjectsPerformSelector method is prefaced as withObject. This indicates you are passing an object, not a primitive float. So wrap the float you want to pass in an NSNumber as such:
NSNumber * numToPass = #(floatToWrap);
[[self gameObjects] makeObjectsPerformSelector:#selector(update:) withObject:numToPass]];
- (void)update:(NSNumber *)dt {
NSLog(#"%f",dt.floatValue); // or [dt floatValue];
}
Hope this helps
As stated by others, you've made some mistake in your attempt to use NSNumbers and would probably be better off asking us to look at that code.
I ran the following:
float value = 0.0034324f;
NSNumber *valueObject = #(value);
NSLog(#"%0.7f, %#", value, valueObject);
Output was:
2013-07-12 17:45:07.948 Untitled[4950:707] 0.0034324, 0.0034324
The issue was that I didn't change my selected method to accomodate an NSNumber, as it still had a float as its parameter type.
Thanks for the help everybody.
[[self gameObjects] makeObjectsPerformSelector:#selector(update:) withObject:[NSNumber numberWithFloat:dt]];
Calls a selector that has a float argument.
Chang the update: argument to NSNumber and inside it call floatValue on the NSNumber
Probably better to just do a for-in loop on your array of gameObjects than all this performSelector and NSNumber business. In the loop call the update netheid directly.
You are looking for NSInvocation. It's not the most pleasant thing to write, but it does exactly what you asked for:
- (void)update:(CGFloat)value
{
XCTAssertEqualsWithAccuracy(value, 2.1, 0.001, #"");
}
- (void)testNSInvocationOverArrayWithFloatArgument
{
CGFloat value = 2.1;
NSArray *gameObjects = #[ self ];
for (id object in gameObjects) {
NSMethodSignature *signature = [object methodSignatureForSelector:#selector(update:)];
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];
[invocation setTarget:object];
[invocation setSelector:#selector(update:)];
[invocation setArgument:&value atIndex:2];
[invocation invoke];
}
}

Iterating a va_list when passed as a parameter to a method in Objective-C

I would like to pass a variable argument list from one method (functionOne) to another (functionTwo). Everything works fine, except that I have not been able to figure out how to setup the va_list in functionTwo in a way where I can access the first parameter in the va_list. Using va_arg advances to the second parameter in the va_list. Thx.
- (void)functionOne:(NSString *)configFiles, ... {
va_list args;
va_start(args, configFiles);
[self functionTwo:args];
va_end(args);
}
- (void)functionTwo:(va_list)files {
NSString *file;
while ((file = va_arg(configFiles, NSString *))) {
...
}
}
The first variadic argument is not the argument passed to va_start – it's the one immediately following it. If you want functionTwo: to have access to the configFiles string, you'll need to pass it in explicitly.
See Technical Q&A QA1405: Variable arguments in Objective-C methods.
Methods that take variable arguments are known as variadic methods.
Keep in mind that the implementation of an Objective-C method is just
a block of code, like a C function. The variadic argument macros
described in the stdarg(3) manual page work the same way in a method
as they do in an ordinary function.
Here's an example of an Objective-C category, containing a variadic
method that appends all the objects in a nil-terminated list of
arguments to an NSMutableArray instance:
#import <Cocoa/Cocoa.h>
#interface NSMutableArray (variadicMethodExample)
// This method takes a nil-terminated list of objects.
- (void)appendObjects:(id)firstObject, ...;
#end
#implementation NSMutableArray (variadicMethodExample)
- (void)appendObjects:(id)firstObject, ... {
id eachObject;
va_list argumentList;
if (firstObject) // The first argument isn't part of the varargs list,
{ // so we'll handle it separately.
[self addObject: firstObject];
// Start scanning for arguments after firstObject.
va_start(argumentList, firstObject);
while (eachObject = va_arg(argumentList, id)) // As many times as we can get an argument of type "id"
[self addObject: eachObject]; // that isn't nil, add it to self's contents.
va_end(argumentList);
}
}
#end
A solution that I use for debugging purposes is like
-(void) debug:(NSString*)format, ... {
if (level < MXMLogLevelDebug) return;
if(format == nil) return;
va_list args, args_copy;
va_start(args, format);
va_copy(args_copy, args);
va_end(args);
NSString *logString = [[NSString alloc] initWithFormat:format
arguments:args_copy];
NSString *funcCaller = #"";
NSArray *syms = [NSThread callStackSymbols];
if ([syms count] > 1) {
funcCaller = [syms objectAtIndex:1];
}
NSString *logMessage = [NSString stringWithFormat:#"%# DEBUG: %#", funcCaller, logString];
NSLog(#"%#",logMessage);
}
The side-effect that this can have is that you have to add a guard on the args to be sure is not NULL.

Why does NSInvocation getReturnValue: lose object?

I need your help. I have some problems with NSInvocation 'getReturnValue:' method. I want to create UIButton programmatically, and even more, I want to create it dynamically using NSInvocation and through passing value through the NSArray (that's why I wrapped UIButtonTypeRoundedRect).
Listing.
NSLog(#"Button 4 pushed\n");//this code executed when button pushed
Class cls = NSClassFromString(#"UIButton");//if exists {define class},else cls=nil
SEL msel = #selector(buttonWithType:);
//id pushButton5 = [cls performSelector:msel withObject:UIButtonTypeRoundedRect];//this code works correctly,but I want to do this by NSInvocation
//---------------------------
NSMethodSignature *msignatureTMP;
NSInvocation *anInvocationTMP;
msignatureTMP = [cls methodSignatureForSelector:msel];
anInvocationTMP = [NSInvocation invocationWithMethodSignature:msignatureTMP];
[anInvocationTMP setTarget:cls];
[anInvocationTMP setSelector:msel];
UIButtonType uibt_ = UIButtonTypeRoundedRect;
NSNumber *uibt = [NSNumber numberWithUnsignedInt:uibt_];
NSArray *paramsTMP;
paramsTMP= [NSArray arrayWithObjects:uibt,nil];
id currentValTMP = [paramsTMP objectAtIndex:0];//getParam from NSArray
NSInteger i=2;
void* bufferTMP;
//if kind of NSValue unwrapp it.
if ([currentValTMP isKindOfClass:[NSValue class]]) {
NSUInteger bufferSize = 0;
NSGetSizeAndAlignment([currentValTMP objCType], &bufferSize, NULL);
bufferTMP = malloc(bufferSize);
[currentValTMP getValue:bufferTMP];//copy currentVal to bufer
[anInvocationTMP setArgument:bufferTMP atIndex:i];// The +2 represents the (self) and (cmd) offsets
}else {
[anInvocationTMP setArgument:&currentValTMP atIndex:i];//Again,+2 represents (self) and (cmd) offsets
}
void* result = malloc([[cls methodSignatureForSelector:msel] methodReturnLength]);
[anInvocationTMP invoke];
[anInvocationTMP getReturnValue:result];
NSLog(#"sizeof(UIButton)=%i,sizeof(result)=%i,methodreturnlength = %i,sizeof(*result)=%i",class_getInstanceSize(NSClassFromString(#"UIButton")),sizeof(result),[[cls methodSignatureForSelector:msel] methodReturnLength],sizeof(*result));
id pushButton5;
pushButton5=result;
//---------------------------
NSLog output: sizeof(UIButton)=140,sizeof(result)=4,methodreturnlength = 4,sizeof(*result)=1
The problem is that value from NSInvocation is pointer of size 4 bytes. It should point to UIButton object,size of 140 bytes. But actually refers to 1 byte data. So what does happen with UIButton object,that should be initialized by 'buttonWithType:'?
Added after getting some answers:
To clarify: I want to get UIButton object, but after this code id pushButton5 = (id) result; ,when I try to work with pushButton5,it causes EXC_BAD_ACCESS. Can someone help me?
Can this happen because of this?
Class cls = NSClassFromString(#"UIButton");
...
[anInvocationTMP setTarget:cls];
It is correct, isn't it?
If you're using ARC, I would replace this:
void* result = malloc([[cls methodSignatureForSelector:msel] methodReturnLength]);
[anInvocationTMP invoke];
[anInvocationTMP getReturnValue:result];
With this:
CFTypeRef result;
[anInvocationTMP invoke];
[anInvocationTMP getReturnValue:&result];
if (result)
CFRetain(result);
UIButton *pushButton5 = (__bridge_transfer UIButton *)result;
The reason is that the invokation's return object is not retained, so it will go away, even if you immediately assign it to an object reference, unless you first retain it and then tell ARC to transfer ownership.
result has type void* and your sizeof(*result) expression is measuing sizeof(void), which apparently yields 1 in your compiler.
To check type of an Objective-C object, use isKindOfClass: method:
id resObj = (id)result;
if ([resObj isKindOfClass:[UIButton class]])
NSLog(#"mazel tov, it's a button");
Just be sure it's really an objective-c object first.
The return value is a UIButton* not a UIButton. Thus everything looks fine in your code.
It's not a problem.
First, getReturnValue: should come after the invocation. So,
[anInvocationTMP getReturnValue:result];
[anInvocationTMP invoke];
should be
[anInvocationTMP invoke];
[anInvocationTMP getReturnValue:result];
Next, you should forget about the size of UIButton itself. What buttonWithType returns is UIButton*, not UIButton. In Objective-C, you should never directly deal with the object itself. You should always work with a pointer to the object.
Finally, (Objective-)C's sizeof operator is purely compile-time operation. So, sizeof(*result) doesn't know at all what result points to at the run time. But it doesn't matter... you shouldn't care about the size of UIButton, as I already told you.
Really answer that I needed was... How do you think where ? Yes, in documentation.
Use the NSMethodSignature method methodReturnLength to determine the size needed for buffer :
NSUInteger length = [[myInvocation methodSignature] methodReturnLength];
buffer = (void *)malloc(length);
[invocation getReturnValue:buffer];
When the return value is an object, pass a pointer to the variable (or memory) into which the object should be placed :
id anObject;
NSArray *anArray;
[invocation1 getReturnValue:&anObject];
[invocation2 getReturnValue:&anArray];
So the problem solved. Thanks for your respond guys.

Objective c implement method which takes array of arguments

Hee
Does anybody know how to implement an method in objective c that will take an array of arguments as parameter such as:
[NSArray arrayWithObjects:#"A",#"B",nil];
The method declaration for this method is:
+ (id)arrayWithObjects:(id)firstObj...
I can't seem to make such method on my own. I did the following:
+ (void) doSometing:(id)string manyTimes:(NSInteger)numberOfTimes;
[SomeClass doSometing:#"A",#"B",nil manyTimes:2];
It will give the warningtoo many arguments to function 'doSometing:manyTimes:'
Thanks already.
The ellipsis (...) is inherited from C; you can use it only as the final argument in a call (and you've missed out the relevant comma in your example). So in your case you'd probably want:
+ (void)doSomethingToObjects:(id)firstObject, ...;
or, if you want the count to be explicit and can think of a way of phrasing it well:
+ (void)doManyTimes:(NSInteger)numberOfTimes somethingToObjects:(id)firstObject, ...;
You can then use the normal C methods for dealing with ellipses, which reside in stdarg.h. There's a quick documentation of those here, example usage would be:
+ (void)doSomethingToObjects:(id)firstObject, ...
{
id object;
va_list argumentList;
va_start(argumentList, firstObject);
object = firstObject;
while(1)
{
if(!object) break; // we're using 'nil' as a list terminator
[self doSomethingToObject:object];
object = va_arg(argumentList, id);
}
va_end(argumentList);
}
EDIT: additions, in response to comments. You can't pass the various things handed to you in an ellipsis to another function that takes an ellipsis due to the way that C handles function calling (which is inherited by Objective-C, albeit not obviously so). Instead you tend to pass the va_list. E.g.
+ (NSString *)doThis:(SEL)selector makeStringOfThat:(NSString *)format, ...
{
// do this
[self performSelector:selector];
// make string of that...
// get the argument list
va_list argumentList;
va_start(argumentList, format);
// pass it verbatim to a suitable method provided by NSString
NSString *string = [[NSString alloc] initWithFormat:format arguments:argumentList];
// clean up
va_end(argumentList);
// and return, as per the synthetic example
return [string autorelease];
}
Multiple arguments (also known as an arglist) can only come at the end of a method declaration. Your doSomething method would look something like this:
+ (void)doNumberOfTimes:(NSInteger)numberOfTimes withStrings:(id)firstArg, ...
{
va_list args;
va_start(args, firstArg);
NSString * argString = firstArg;
while (argString != nil)
{
// do something with argString here
argString = va_arg(args, NSString *);
}
va_end(args);
}
To be called as follows:
[SomeClass doNumberOfTimes:2 withStrings:#"A", #"B", nil];
See also: How to create variable argument methods in Objective-C
I think you're after a variadic function. Here's Apple's documentation: http://developer.apple.com/library/mac/qa/qa2005/qa1405.html

#selector - With Multiple Arguments?

I have been using #selector today for the first time and have not been able to work out how to do the following? How would you write the #selector if you had more than one argument?
No arguments:
-(void)printText {
NSLog(#"Fish");
}
[self performSelector:#selector(printText) withObject:nil afterDelay:0.25];
Single argument:
-(void)printText:(NSString *)myText {
NSLog(#"Text = %#", myText);
}
[self performSelector:#selector(printText:) withObject:#"Cake" afterDelay:0.25];
Two arguments:
-(void)printText:(NSString *)myText andMore:(NSString *)extraText {
NSLog(#"Text = %# and %#", myText, extraText);
}
[self performSelector:#selector(printText:andMore:) withObject:#"Cake" withObject:#"Chips"];
Multiple Arguments: (i.e. more than 2)
NSInvocation
- (id)performSelector:(SEL)aSelector
withObject:(id)anObject
withObject:(id)anotherObject
From the Documentation:
This method is the same as performSelector: except that you can supply two arguments for aSelector. aSelector should identify a method that can take two arguments of type id. For methods with other argument types and return values, use NSInvocation.
so in your case you would use:
[self performSelector:#selector(printText:andMore:)
withObject:#"Cake"
withObject:#"More Cake"]
As an alternative for NSInvocation when you have more than two parameters, you can use NSObject's -methodForSelector: as in the following example:
SEL a_selector = ...
Type1 obj1 = ...
Type2 obj2 = ...
Type3 obj3 = ...
typedef void (*MethodType)(id, SEL, Type1, Type2, Type3);
MethodType methodToCall;
methodToCall = (MethodType)[target methodForSelector:a_selector];
methodToCall(target, a_selector, obj1, obj_of_type2, obj_of_type3);
I had an issue where I needed to use the afterDelay along with multiple arguments to my #selector method. Solution? Use a wrapper function!
Say this is the function I want to pass to #selector:
-(void)myFunct:(NSString *)arg1 andArg:(NSString *)arg2 andYetAnotherArg:(NSString *)arg3;
Obviously, I can't even use withObject: withObject: here, so, make a wrapper!
-(void)myFunctWrapper:(NSArray *)myArgs {
[self myFunct:[myArgs objectAtIndex:0] andArg:[myArgs objectAtIndex:1] andYetAnotherArg:[myArgs objectAtIndex:2]];
}
and use it by doing:
NSArray *argArray = [NSArray arrayWithObjects:string1,string2,string3,nil];
[self performSelector:#selector(myFunctWrapper:) withObject:argArray afterDelay:1.0];
This way I can have multiple arguments and use the selector with delay.
#selector(printText:andMore:)
[self performSelector:#selector(printText:andMore) withObject:#"Cake" withObject:#"More Cake"];
Another option is to use an even shorter syntax:
#import <objc/message.h> // objc_msgSend
...
((void (*)(id, SEL, Type1, Type2, Type3))objc_msgSend)(target, a_selector, obj1, obj_of_type2, obj_of_type3);
Elaborating on Ben-Uri's answer, which can be written way shorter.
E.g. calling the UIView method - (CGPoint)convertPoint:(CGPoint)point toView:(UIView *)view can
be done as follows:
SEL selector = #selector(covertPoint:toView:);
IMP method = [viewA methodForSelector:selector];
CGPoint pointInB = method(viewA, selector, pointInA, viewB);
As KennyTM pointed out, the selector syntax is
#selector(printText:andMore:)
You call it with
performSelector:withObject:withObject.
... if you need more arguments or different types, you need to use NSIvocation
Using NSInvocation as you specify you can create an NSObject category that implements
- (void)performSelector:(SEL)aSelector withObjects:(NSArray *)arguments;
Something like:
- (void)performSelector:(SEL)aSelector withObjects:(NSArray *)arguments
{
NSMethodSignature *signature = [self methodSignatureForSelector: aSelector];
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature: signature];
[invocation setSelector: aSelector];
int index = 2; //
for (NSObject *argument in arguments) {
[invocation setArgument: &argument atIndex: index];
index ++;
}
[invocation invokeWithTarget: self];
}
from: iOS - How to implement a performSelector with multiple arguments and with afterDelay?