问题
I'm sure this is a simple question, but how can I call a function with [self MyFunction]; where 'MyFunction' is a NSString? I want to call functions using various variables which, when joined, form the function name (ie. FunctionName1, FunctionName2, etc.)
For example (simplified):
NSString *MyStringValue=@"FunctionName";
int MyNumber = 1;
NSString *MyFunction=[myStringValue stringByAppendingFormat:@"%d ",myNumber];
So I'm looking to call the function "FunctionName1" using:
[self MyFunction];
but that doesn't work. Can anyone help?
EDIT: Here's the full code that now works:
-(void)getnewblock {
NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];
NSNumber *actionblockload = nil;
actionblockload = [standardUserDefaults objectForKey:@"actionblock"];
int actionblock = [actionblockload intValue];
NSString *block=@"setblock";
NSString *blockanimate=@"blockanimate";
NSString *blocktochange=[block stringByAppendingFormat:@"%d",actionblock];
NSString *blocktoanimate=[blockanimate stringByAppendingFormat:@"%d",actionblock];
SEL sel1 = NSSelectorFromString(blocktochange);
SEL sel2 = NSSelectorFromString(blocktoanimate);
[self performSelector:sel1];
[self performSelector:sel2];
[self setblockimages];
}
The only thing is I get the 'may cause a leak' message - although the app runs fine.
回答1:
Welcome to Stackoverflow Mark.
In Cocoa Touch, what you refer to as a "function" is called "selector" (a method that has both a signature and a target) and has its own type SEL. In order to achieve what you want you need to first get the selector by name and then perform it. Here is some code to get you started:
-(void) yourMainMethod{
NSString * methodName = @"calculateAcceleration";
SEL sel = NSSelectorFromString(methodName);
[self performSelector:sel];
}
-(void)calculateAcceleration
{
NSLog(@"Called!");
}
回答2:
You can use as below
SEL function = @selector(testFunction);
[self performSelector:function];
-(void)testFunction {
NSLog(@"ABC Test");
}
But Not Call NSString via self as function.
thanks
回答3:
In my opinion, it is not possible to have "NSString" as a method name.
But, you can have conditional checks so as to select a proper method that has to be executed.
回答4:
Nsstring *newNsstring;
int *YourInt;
newNsstring =[NSString stringWithFormat:@"%@%d",yourNsstringName,yourInt,nil];
then you can edit only your new NSString but i dont think you can make it ur method's name
回答5:
If one can
NSString *stringMethode = @"MyMethodName"
SEL mySelector = NSSelectorFromString(stringMethode);
if([self respondsToSelector:mySelector]){
[self performSelector:mySelector withObject:nil];
}else{
//error not method
}
- (void)MyMethodName
{
//call methode :)
}
Good luck ;)
来源:https://stackoverflow.com/questions/13528643/using-nsstring-to-call-a-function-in-xcode-4-x