Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

trey5498

macrumors regular
Original poster
Jun 16, 2008
191
0
I am trying to call a method that I have done successfully and set up fine. The problem comes in the basic calling with a variable.

Code:
NSString *stTmp;
for (i=0; i<[arrPRNint count]; i++) {
    stTmp = [arrPRNint objectAtIndex: i];
    [prninstall stTmp];
}

obviously this doesnt work, should it be [prninstall "stTmp"]; or how do I let that know it is a variable and that it should read the value and not literally?
 
Variables in ObjC are not directly accessible via the messaging system. You would have to implement Accessor/Mutator methods in order to gain access unless you are writing code within the implementation of that class. If that is the case, you can directly access it.
 
Is prninstall an object or a method here? The syntax for method calls is
Code:
[<object> <method>:<firstvariable> <secondmethodpart>:<secondvariable>];

If prninstall is the name of the method you need to supply which object you are messaging. If it is an object you need to supply the method you want to call.

I suspect that prninstall is a method in the current class and you are trying ot message the current object. In that case you want to use

Code:
[self prninstall:stTmp];
 
Code:
#Import "PrnIntall.h"

the prninstall is the file or i guess in this case the object and the method inside would be a printer like "printer1"

the way I called one at a time was:

Code:
[prninstall printer1];
 
Ah OK so you are trying to use the value of the string as the selector right? So, for example, stTmp is @"printer1" right? If this is the case you have to see the difference between a string you type into the file that the compiler has access to and a NSString object? You cannot directly use a NSString object as a selector.

You can turn a string into a selector with NSSelectorFromString(). Once you have a selector you can use the Obj-C runtime functions to message an object with that selector. The function you need is objc_msgSend

So putting it all together we get something like this:

Code:
NSString *stTmp;
for (i=0; i<[arrPRNint count]; i++) {
    stTmp = [arrPRNint objectAtIndex: i];
    objc_msgSend(prninstall, NSSelectorFromString(stTmp));
}

@robbie I've added the general form to the [guide]Objective-C tutorial[/guide] guide.

Cool :cool:
 
I think I have an idea of what you are trying to do, and what you are looking for is a Core Foundation function called NSSelectorFromString.

Something like this is what you are looking for:

Code:
NSString *stTmp;
SEL aMethod;

stTmp = [someArray objectAtIndex: 1];  //assuming this is an array of NSString objects
aMethod = NSSelectorFromString( stTmp );  //set the selector for the string

[prninstall performSelector:aMethod];  //send a message to prninstall to perform the selector
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.