Is there something like a Matlab eval statement in Objective-C 2.0?

I am new to Objective-C and I am looking for the eval instruction as I used in Matlab.

If you are not familiar with this, you can create a character string, and then eval this string, which treats it like a line of code.

Here is an example where you want to change the background color of one of the four buttons based on the variable foo, which is = 3, and the buttons will have the name button1, button2, etc.

 NSString* buttonEval = [[NSString alloc] initWithFormat:@"[button%d setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];", foo] 

Is there an instruction that will evaluate this line as if it were a line of code?

+4
source share
4 answers

No; although Objective-C is a dynamically typed language, it is still a compiled language and not interpreted, unlike a language such as Javascript or PHP, for example.

In the above example, you can use an array to store pointers to UIButton instances:

 buttonArray = [[NSMutableArray alloc] init]; ... UIButton *aButton; //Reference to a UIButton instance [buttonArray addObject:aButton]; 

And then return the pointer to the UIButton you want to call the method on.

 [[buttonArray objectAtIndex:foo] setTitleColor:[UIColor blackColor] forState:UIControlStateNormal]; 
+6
source

This is not an ordinary function in compiled languages that Objective-C qualifies as. This is because the mechanisms and "intelligence" necessary to convert the source code into something that the CPU can run are contained in a compiler that no longer works when the code is executed.

+14
source

Objective-C 2.0 lacks the eval instruction; But; There are several alternative ways open for you.

In this particular case, you most likely want to call iteration as well; as mentioned in Perspx.

In a more general case; calls are created from selectors, and selectors can be created from strings; objects can, provided that they are given a name, be tracked and, as such, despite the Objective-C being a compiled language; creating an eval function is quite possible.

+8
source

Ok, keep it Short and Simple : just use a switch, an if / then clause, or an array of buttons.

In any case, if you want something really cool related to the eval statements in Objective-C, see the code injection .

(just kidding);)

0
source

All Articles