Selector function with int parameter? - objective-c

Using Cocos2d-iphone, and objective-c game development framework.
I create a button with:
CCMenuItemImage *slot = [CCMenuItemImage itemFromNormalImage:#"BattleMoveSelectionSlot1.png"
selectedImage:#"BattleMoveSelectionSlot2.png"
target:self selector:#selector(moveChosen:i)];
And my moveChosen method is:
-(void)moveChosen:(int)index {
}
However, for some reason I get an error on #selector(moveChosen:i) where i is an integer. How, then, may I pass an integer parameter to my function when the button is pressed?
The error is
Expected ':'

Georg is correct. Note that as implemented, this will invoke undefined behaviour since index is an int but the action method it's being used as expects an object (id) there, not an int. The signature of an action method is:
- (void)methodName:(id)sender;
Or, when used with Interface Builder:
- (IBAction)methodName:(id)sender;
(IBAction is an alias of void. The two are semantically different but functionally identical.)
Where sender is the object that sent the action message--in this case, the object you created and assigned to the slot variable.

You don't include any argument names in the selector:
#selector(moveChosen:)
Selectors don't allow for binding parameters.

Georg is partially correct. For your example, it would be:
#selector(moveChosen:)
But note: if you have more than one parameter, you do include the formal parameter names to get the selector. If your function signature were:
- (void)moveChosen:(int)index withThing:(Thing*)thing
then the selector would be:
#selector(moveChosen:withThing:)

The selector is just the name of the message that you want to send. The arguments will be provided when it is called — which means CCMenuItemImage will decide what argument is passed. If CCMenuItemImage does not support providing an integer parameter, you can't make it do that.

Related

Passing a variable number of arguments to a selector

I would like to invoke a selector from a method containing a vargs parameter list. Is there a way to dynamically provide a variable of number of parameters to a selector?
Unfortunately when using performSelector, your only option for passing multiple parameters is to pass in a NSArray or NSDictionary, etc. Obviously you then have to change the receiving method's constructor to accept that new parameter-storing object.
Alternatively, you could look into using NSInvocation.
You can pass a NSMutableDictionary where you can have a number of parameters.

Objective-C Selector pointer to be passed to a C function

I have a C struct that contains a function pointer. Now, I have used this setup within C with no problems, but now I'm using this C struct in Objective-C and I need to pass a function (or selector) pointer that is defined in the Objective-C class.
1. Here is what I have for the Objective-C selector that needs to be passed as a pointer to the C function:
- (void)myObjCSelector:(int*)myIntArray
{
// Do whatever I need with myIntArray
}
2. And here is where I run into a wall, Within Objective-C I'm trying to pass the selector as a pointer to the C function call: In place of "myObjCSelectorPointer" I need the proper syntax to pass the selector as a function pointer in this C function call:
passObjCSelectorPointerToCContext(cContextReference, myObjCSelectorPointer);
I did investigate this issue, but could mainly find several different ways of doing similar things, but I couldn't find anything specific for calling C functions and passing an Objective-C selector pointer.
In objc a selector is not a function pointer. A selector is a unique integer that is mapped to a string in a method lookup table stored by the objc runtime. In the above case your method name would be myObjCSelector: and to get the unique selector for it you would type #selector(myObjCSelector:). However this would be of no use to you because it doesnt represent a particular implementation of a function.
What youre looking for is IMP. Refer to this SO question.
EDIT 2:
IMP myObjCSelectorPointer = (void (*)(id,SEL,int*))[self methodForSelector:#selector(myObjCSelector:)];
Then you can call the method using
myObjCSelectorPointer(self,#selector(myObjCSelector:),myIntArray);
However, what this means you will need to make sure that you add the pointer to self in the c function call passObjCSelectorPointerToCContext.
So it should look like this
passObjCSelectorPointerToCContext(cContextReference, self, myObjCSelectorPointer);
when called from within the object that contains the method.
It is important to note though that using IMP is almost never the right technique. You should try to stick with pure Obj-C. Obj-C is quite efficient after the first call to a message because it uses temporal caching.
EDIT 1:
It's useful to understand why objc works in this way. The Apple documents explain it in depth. However a short explanation is as follows:
When you send a message to an object such as [myobject somemethod] the compiler won't immediately know which particular implementation of somemethod to call because there might be multiple classes with multiple overriden versions of somemethod. All of those methods have the same selector, irrespective of its arguments and return values and hence the decision about which implementation of somemethod is deffered to when the program is running. [myobject somemethod] gets converted by the compiler into a C function call:
objc_msgSend(myobject, #selector(somemethod))
This is a special function that searches each myobject class layout to see whether that class knows how to respond to a somemethod message. If not it then searches that class's parent and so on until the root. If none of the classes can respond to somemethod then NSObject defines a private method called forward where all unknown messages are sent.
Assuming that a class can respond to the somemethod message then it will also have a particular pointer of type IMP that points to the actual implementation of the method. At that point the method will be called.
There is considerably more to this procedure than I have described but the outline should be enough to help you understand what the goal of a selector is.
One final point is that the reason method names are mapped to unique integers via the #selector directive is so that the runtime doesn't have to waste time doing string comparisons.
Basically, the answer is: Objective-C selectors are different from function pointers. You need two pieces of data to perform a selector. That is an object and the selector itself. You will need some glue to accomplish your task.
Check this question.
Do you have to use a function pointer? In Objective-C, you can get the function pointer to an arbitrary method implementation (known as an IMP), but this is extremely uncommon, and usually not a good idea. Calling objc_msgSend() directly is also not the greatest idea, because there are several different variants of objc_msgSend(), and the compiler automatically chooses different ones to use based on the return type of the method. Methods that return an object go through objc_msgSend(), but objects that return structs might go through objc_msgSend() or they might go through objc_msgSend_stret(). And if the method returns a double, then it goes through objc_msgSend_fpret()...
Documentation: Objective-C Runtime Reference: Sending Messages
Instead, I might recommend using a target-action pair, or using a block. Then you might do something like:
myContextRef->target = anObjcObject;
myContextRef->action = #selector(invokeMe:);
And when you're done, do:
[myContextRef->target performSelector:myContextRef->action withObject:someReturnInformation];
Or maybe use a block:
myContextRef->completionHandler = [^(id returnInformation) {
[anObjcObject invokeMe:returnInformation];
} copy];
And then when you're done, do:
myContextRef->completionHandler(someReturnInformation);
(and don't forget to -release the block when you free the context)

How to call a method with parameters using #selector

I have two methods with same name but different parameters say:
-(void)methodA:(NSString*)string
-(void)methodA:(NSNotification*)notification
Now i need to call those methods using #selector with the parameters. How to do it ?
SEL aSel = #selector(methodA:);
[objectTakesString performSelector:aSel withObject:#"A string!"];
[objectTakesNtfctn performSelector:aSel withObject:[NSNotification notificationWith...]];
-[NSObject performSelector:withObject:] takes both the selector to be invoked, and a pointer to the parameter to pass it.
In my opinion, both the preceding answers are wrong. If you use
-[NSObject performSelector:withObject:];
as Sixten Otto suggests, you would have to place this at the beginning of your method:
-(void)methodA:(id)stringOrNotification
{
if ([stringOrNotification isKindOfClass:[NSString class])
{
..do something..
}
if ([stringOrNotification isKindOfClass:[NSNotification class])
{
..do something else..
}
. . .
}
Apart from this (bad) approach, what you're asking for can't in fact (easily) be done in Objective-C, because the language doesn't support parametric polymorphism. In other words, the type information is not used in the message dispatch. Yet another way to say this is that there can't be "two methods with same name but different parameters" in the same class. In fact, I'm surprised that you haven't yet seen a compiler error if you tried to declare this.
(If you've got the two methods defined on different classes, as dreamlax seems to assume, the message invocation will work trivially, even if you don't use performSelector:. Like so:
id eitherStringOrNotification;
[objectOfUncertainClass methodA:eitherStringOrNotification];
If that's what you're asking for, you don't have a problem.
)
Note that the NSMethodSignature object does contain information about the parameter types, but it's generated by the receiving object, so you can't really use it to distinguish between messages based on what parameter types are handed in (since that information is not available when the method signature is instantiated).

How do I pass multiple parameters in Objective-C?

I have read several of the post about Objective-C method syntax but I guess I don't understand multiple names for a method.
I'm trying to create a method called getBusStops with NSString and NSTimeInterval parameters and a return type of NSMutableArray. This is how I have constructed the method but it obviously gets errors at runtime:
- (NSMutableArray *)getBusStops:(NSString *)busStop
(NSTimeInterval *)timeInterval;
I saw another example with a method:
-(NSInteger)pickerView:(UIPickerView *)pickerView
numberOfRowsInComponent:(NSInteger)component
I don't understand why this method has a method name for each parameter. Should I do the same with something like:
- (NSMutableArray *)getBusStops:(NSString *)busStop
forTime:(NSTimeInterval *)timeInterval
You need to delimit each parameter name with a ":" at the very least. Technically the name is optional, but it is recommended for readability. So you could write:
- (NSMutableArray*)getBusStops:(NSString*)busStop :(NSTimeInterval*)timeInterval;
or what you suggested:
- (NSMutableArray*)getBusStops:(NSString*)busStop forTime:(NSTimeInterval*)timeInterval;
Objective-C doesn't have named parameters, so everything on the left side of a colon is part of the method name. For example,
getBusStops: forTime:
is the name of the method. The name is broken up so it can be more descriptive. You could simply name your method
getBusStops: :
but that doesn't tell you much about the second parameter.
Yes; the Objective-C method syntax is like this for a couple of reasons; one of these is so that it is clear what the parameters you are specifying are. For example, if you are adding an object to an NSMutableArray at a certain index, you would do it using the method:
- (void)insertObject:(id)anObject atIndex:(NSUInteger)index;
This method is called insertObject:atIndex: and it is clear that an object is being inserted at a specified index.
In practice, adding a string "Hello, World!" at index 5 of an NSMutableArray called array would be called as follows:
NSString *obj = #"Hello, World!";
int index = 5;
[array insertObject:obj atIndex:index];
This also reduces ambiguity between the order of the method parameters, ensuring that you pass the object parameter first, then the index parameter. This becomes more useful when using functions that take a large number of arguments, and reduces error in passing the arguments.
Furthermore, the method naming convention is such because Objective-C doesn't support overloading; however, if you want to write a method that does the same job, but takes different data-types, this can be accomplished; take, for instance, the NSNumber class; this has several object creation methods, including:
+ (id)numberWithBool:(BOOL)value;
+ (id)numberWithFloat:(float)value;
+ (id)numberWithDouble:(double)value;
In a language such as C++, you would simply overload the number method to allow different data types to be passed as the argument; however, in Objective-C, this syntax allows several different variants of the same function to be implemented, by changing the name of the method for each variant of the function.
The text before each parameter is part of the method name. From your example, the name of the method is actually
-getBusStops:forTime:
Each : represents an argument. In a method call, the method name is split at the :s and arguments appear after the :s. e.g.
[getBusStops: arg1 forTime: arg2]
for create method:
-(void)mymethods:(NSString *)aCont withsecond:(NSString *)a-second {
//method definition...
}
for call the method:
[mymethods:self.contoCorrente withsecond:self.asecond];
(int) add: (int) numberOne plus: (int) numberTwo ;
(returnType) functionPrimaryName : (returnTypeOfArgumentOne) argumentName functionSecondaryNa
me:
(returnTypeOfSecontArgument) secondArgumentName ;
as in other languages we use following syntax
void add(int one, int second)
but way of assigning arguments in OBJ_c is different as described above

Selectors in Objective-C?

First, I'm not sure I really understand what a selector is. From my understanding, it's the name of a method, and you can assign it to a class of type 'SEL' and then run methods such as respondToSelector to see if the receiver implements that method. Can someone offer up a better explanation?
Secondly, to this point, I have the following code:
NSString *thing = #"Hello, this is Craig";
SEL sel = #selector(lowercaseString:);
NSString *lower = (([thing respondsToSelector:sel]) ? #"YES" : #"NO");
NSLog (#"Responds to lowercaseString: %#", lower);
if ([thing respondsToSelector:sel]) //(lower == #"YES")
NSLog(#"lowercaseString is: %#", [thing lowercaseString]);
However, even though thing is clearly a kind of NSString, and should respond to lowercaseString, I cannot get the 'respondsToSelector' conditional to return "YES"...
You have to be very careful about the method names. In this case, the method name is just "lowercaseString", not "lowercaseString:" (note the absence of the colon). That's why you're getting NO returned, because NSString objects respond to the lowercaseString message but not the lowercaseString: message.
How do you know when to add a colon? You add a colon to the message name if you would add a colon when calling it, which happens if it takes one argument. If it takes zero arguments (as is the case with lowercaseString), then there is no colon. If it takes more than one argument, you have to add the extra argument names along with their colons, as in compare:options:range:locale:.
You can also look at the documentation and note the presence or absence of a trailing colon.
Selectors are an efficient way to reference methods directly in compiled code - the compiler is what actually assigns the value to a SEL.
Other have already covered the second part of your q, the ':' at the end matches a different signature than what you're looking for (in this case that signature doesn't exist).
That's because you want #selector(lowercaseString), not #selector(lowercaseString:). There's a subtle difference: the second one implies a parameter (note the colon at the end), but - [NSString lowercaseString] does not take a parameter.
In this case, the name of the selector is wrong. The colon here is part of the method signature; it means that the method takes one argument. I believe that you want
SEL sel = #selector(lowercaseString);
NSString's method is lowercaseString (0 arguments), not lowercaseString: (1 argument).
Don't think of the colon as part of the function name, think of it as a separator, if you don't have anything to separate (no value to go with the function) then you don't need it.
I'm not sure why but all this OO stuff seems to be foreign to Apple developers. I would strongly suggest grabbing Visual Studio Express and playing around with that too. Not because one is better than the other, just it's a good way to look at the design issues and ways of thinking.
Like
introspection = reflection
+ before functions/properties = static
- = instance level
It's always good to look at a problem in different ways and programming is the ultimate puzzle.
From my understanding of the Apple documentation, a selector represents the name of the method that you want to call. The nice thing about selectors is you can use them in cases where the exact method to be called varies. As a simple example, you can do something like:
SEL selec;
if (a == b) {
selec = #selector(method1)
}
else
{
selec = #selector(method2)
};
[self performSelector:selec];
As per apple docs:
https://developer.apple.com/library/archive/documentation/General/Conceptual/DevPedia-CocoaCore/Selector.html
A selector is the name used to select a method to execute for an object, or the unique identifier that replaces the name when the source code is compiled. A selector by itself doesn’t do anything. It simply identifies a method. The only thing that makes the selector method name different from a plain string is that the compiler makes sure that selectors are unique. What makes a selector useful is that (in conjunction with the runtime) it acts like a dynamic function pointer that, for a given name, automatically points to the implementation of a method appropriate for whichever class it’s used with. Suppose you had a selector for the method run, and classes Dog, Athlete, and ComputerSimulation (each of which implemented a method run). The selector could be used with an instance of each of the classes to invoke its run method—even though the implementation might be different for each.
Example:
(lldb) breakpoint --set selector viewDidLoad
This will set a breakpoint on all viewDidLoad implementations in your app.
So selector is kind of a global identifier for a method.