Objective C equivalent of C method signature - objective-c

I want make a function to include in my code to calculate percentages.
In Php, it's :
function percent(a,b){
return a/b*100;
}
In Objective C, I don't know. I tried:
-(void)percent(a,b){
return a/b*100;
}
But there are 2 errors. Could you me explain how to make it work?
Thank you for you help

A method is defined in a slightly different syntax than you're used to:
- (float)percentWithA:(float)a dividedByB:(float)b
{
return a / b * 100;
}
The parameters are "strewn" throughout the method call. For instance, this method's name would be percentWithA:dividedByB:. You don't need to be as explicit as this call, however. For example, you could do this:
- (float)percent:(float)a :(float)b { /* ... */ }
But it doesn't provide much context.

The more correct way to do this will be:
- (float)precentageByDevidingFloat:(float)a byFloat:(float)b {
float returnValue = 0;
if (b != 0)
returnValue = a / b * 100;
return returnValue;
}
This way you use a more correct naming convention , you actually return a float and your safe in case some one gave you the value 0 in B.
(which should be covered by documentation)

You could also do it like this, with a C function:
// in your .h
float percent(float a, float b);
// in your .m or .c
float percent(float a, float b)
{
return a / b * 100.0f;
}
Or, if you are into macros:
// remember to always enclose macros in parentheses
#define percent(a, b) (a / b * 100.0f)
And you would call it like this:
percent(50, 20);

Objective-C uses a strange convention of having parameter names as part of a method name and therefore parameter declarations are embedded in a method name.
-(float)percentOf:(float)a over:(float)b
{
return (a/b) * 100.0;
}
The first type in parentheses defines the return type, the parameters come after colons and also have their type in parentheses.

Related

understanding a piece of code with ``boolean`` and ``switch``

i was looking some examples of interactions with the keyboard and stumbled upon this code that i found interesting. But i'm having trouble understanding a certain part of it(it's marked down below).I don't get how all this whole ''boolean'' declaration, ''switch'' and ''CASE'' works, i tried to look in the reference but still. Could someone explain in a simple maner how these work?
float x = 300;
float y = 300;
float speed = 5;
boolean isLeft, isRight, isUp, isDown;
int i = 0;
void keyPressed() {
setMove(keyCode, true);
if (isLeft ){
x -= speed;
}
if(isRight){
x += speed;
}
}
void keyReleased() {
setMove(keyCode, false);
}
boolean setMove(int k, boolean b) {// <<<--- From this part down
switch (k) {
case UP:
return isUp = b;
case DOWN:
return isDown = b;
case LEFT:
return isLeft = b;
case RIGHT:
return isRight = b;
default:
return b; }
}
Questions like these are best answered by the reference:
Works like an if else structure, but switch() is more convenient when you need to select between three or more alternatives. Program controls jumps to the case with the same value as the expression. All remaining statements in the switch are executed unless redirected by a break. Only primitive datatypes which can convert to an integer (byte, char, and int) may be used as the expression parameter. The default is optional.
The rest of the code is setting the corresponding variable to whatever value you passed in as the b parameter, and then returning it.
You should get into the habit of debugging your code. Add print statements to figure out exactly what the code is doing.

Structure of a block declaration

When declaring a block what's the rationale behind using this syntax (i.e. surrounding brackets and caret on the left)?
(^myBlock)
For example:
int (^myBlock)(int) = ^(int num) {
return num * multiplier;
};
C BLOCKS: Syntax and Usage
Variables pointing to blocks take on the exact same syntax as variables pointing to functions, except * is substituted for ^. For example, this is a function pointer to a function taking an int and returning a float:
float (*myfuncptr)(int);
and this is a block pointer to a block taking an int and returning a float:
float (^myblockptr)(int);
As with function pointers, you'll likely want to typedef those types, as it can get relatively hairy otherwise. For example, a pointer to a block returning a block taking a block would be something like void (^(^myblockptr)(void (^)()))();, which is nigh impossible to read. A simple typedef later, and it's much simpler:
typedef void (^Block)();
Block (^myblockptr)(Block);
Declaring blocks themselves is where we get into the unknown, as it doesn't really look like C, although they resemble function declarations. Let's start with the basics:
myvar1 = ^ returntype (type arg1, type arg2, and so on) {
block contents;
like in a function;
return returnvalue;
};
This defines a block literal (from after = to and including }), explicitly mentions its return type, an argument list, the block body, a return statement, and assigns this literal to the variable myvar1.
A literal is a value that can be built at compile-time. An integer literal (The 3 in int a = 3;) and a string literal (The "foobar" in const char *b = "foobar";) are other examples of literals. The fact that a block declaration is a literal is important later when we get into memory management.
Finding a return statement in a block like this is vexing to some. Does it return from the enclosing function, you may ask? No, it returns a value that can be used by the caller of the block. See 'Calling blocks'. Note: If the block has multiple return statements, they must return the same type.
Finally, some parts of a block declaration are optional. These are:
The argument list. If the block takes no arguments, the argument list can be skipped entirely.
Examples:
myblock1 = ^ int (void) { return 3; }; // may be written as:
myblock2 = ^ int { return 3; }
The return type. If the block has no return statement, void is assumed. If the block has a return statement, the return type is inferred from it. This means you can almost always just skip the return type from the declaration, except in cases where it might be ambiguous.
Examples:
myblock3 = ^ void { printf("Hello.\n"); }; // may be written as:
myblock4 = ^ { printf("Hello.\n"); };
// Both succeed ONLY if myblock5 and myblock6 are of type int(^)(void)
myblock5 = ^ int { return 3; }; // can be written as:
myblock6 = ^ { return 3; };
source: http://thirdcog.eu/pwcblocks/
I think the rationale is that it looks like a function pointer:
void (*foo)(int);
Which should be familiar to any C programmer.

get multiple output from a single method in Objective-c

I have my own class and am writing a method with multiple input (three float values) and multiple output (three float values). I don't figure out how I can get multiple output from a single method. Any ideas?
My current method looks like this:
- (void)convertABC2XYZA:(float)a
B:(float)b
C:(float)c
outputX:(float)x
outputY:(float)y
outputZ:(float)z
{
x = 3*a + b;
y = 2*b;
z = a*b + 4*c;
}
One way to “return” multiple outputs is to pass pointers as arguments. Define your method like this:
- (void)convertA:(float)a B:(float)b C:(float) intoX:(float *)xOut Y:(float *)yOut Z:(float)zOut {
*xOut = 3*a + b;
*yOut = 2*b;
*zOut = a*b + 4*c;
}
and call it like this:
float x, y, z;
[self convertA:a B:b C:c intoX:&x Y:&y Z:&z];
Another way is to create a struct and return it:
struct XYZ {
float x, y, z;
};
- (struct XYZ)xyzWithA:(float)a B:(float)b C:(float)c {
struct XYZ xyz;
xyz.x = 3*a + b;
xyz.y = 2*b;
xyz.z = a*b + 4*c;
return xyz;
}
Call it like this:
struct XYZ output = [self xyzWithA:a B:b C:c];
Methods in Objective-C (unlike, say, Python or JavaScript) can only return at most 1 thing. Create a "thing" to contain the 3 floats you want to return, and return one of those instead.
Instead of returning, you can use output parameters.
This is more related to C than objective-c.
You need to pass the values by references. Your function should be declared like this:
- (void)convertABC2XYZA:(float)a
B:(float)b
C:(float)c
outputX:(float *)x
outputY:(float *)y
outputZ:(float *)z;
and called like this:
[receiver convertABC2XYZA:a B:b C:c outputX:&x outputY:&y outputZ:&z];

Convert methods from Java-actionscript to ObjectiveC

I'm tring to convert the following 3 methods from java-actionscript to Objective C.
Part of my confusion I think is not knowing what Number types, primitives I should be using. ie in actionscript you have only Number, int, and uint. These are the 3 functions I am trying to convert
public function normalize(value:Number, minimum:Number, maximum:Number):Number
{
return (value - minimum) / (maximum - minimum);
}
public function interpolate(normValue:Number, minimum:Number, maximum:Number):Number
{
return minimum + (maximum - minimum) * normValue;
}
public function map(value:Number, min1:Number, max1:Number, min2:Number, max2:Number):Number
{
return interpolate( normalize(value, min1, max1), min2, max2);
}
This is what I have so far
-(float) normalize:(float*)value
withMinimumValue:(float*)minimum
withMaximumValue:(float*)maximum
{
return (value - minimum) / (maximum - minimum);
}
-(float) interpolate:(float*)normValue
withMinimumValue:(float*)minimum
withMaximumValue:(float*)maximum
{
return minimum + (maximum - minimum) * normValue;
}
-(float) map:(float*)value
withMinimumValue1:(float*)min1
withMaximumValue1:(float*)max1
withMinimumValue2:(float*)min2
withMaximumValue2:(float*)max2
{
return interpolate( normalize(value, min1, max1), min2, max2);
}
If you're looking for a primitive type (not an object) that can handle non-integer values, float is probably fine (or CGFloat, as suggested by Chris)
unless your functions need to modify their arguments, you want the arguments to be just float not float *.
you are mixing up Objective-C message passing and plain C function invocation syntax: your example declares them as instance methods, but you're calling them like a function (won't work).
To match your declarations, the invocation would look something like:
return [self interpolate:
[self normalize:value withMinimumValue:min1 withMaximumValue:max1]
withMinimumValue:min2
withMaximumValue:max2];
Because your interpolate, normalize, and map methods do not rely on any variables from the current object instance, they might be better off as objective-C class methods (or even as plain C functions).
Given that none of your methods require any other state to work, all are basic math kinda stuff, and all are pretty straightforward, I would skip Objective-C entirely and just go with straight C. Something like:
static inline float normalize(float val, float min, float max) {
return (val - min) / (max - min);
}
Stick that in a header file somewhere in your project and be done with it. Do the same for interpolate and map.
Note: as others have mentioned, you might want to change the type to CGFloat, if needed.
Assuming you're using Apple's frameworks, these are the conversions you'll probably want to use:
Number =~ CGFloat
int =~ NSInteger
uint =~ NSUInteger

function with multiple arguments

how to pass multiple arguments in a single function in Objective-C? I want to pass 2 integer values and the return value is also integer. I want to use the new Objective-C syntax, not the old C/C++ syntax.
In objective-c it is really super easy. Here is the way you would do it in C:
int functName(int arg1, int arg2)
{
// Do something crazy!
return someInt;
}
This still works in objective-c because of it's compatibility with C, but the objective-c way to do it is:
// Somewhere in your method declarations:
- (int)methodName:(int)arg1 withArg2:(int)arg2
{
// Do something crazy!
return someInt;
}
// To pass those arguments to the method in your program somewhere:
[objectWithOurMethod methodName:int1 withArg2:int2];
Best of luck!
Since this is still google-able and there are better solutions than the accepted answer; there's no need for the hideous withArg2 – just use colons:
Declaration:
#interface
-(void) setValues: (int)v1 : (int)v2;
Definition:
#implementation
-(void) setValues: (int)v1 : (int)v2 {
//do something with v1 and v2
}
Like this:
int sum(int a, int b) {
return a + b;
}
Called like this:
int result;
result = sum(3, 5);
// result is now 8
More here
int add (int a, int b)
{
int c;
c = a + b;
return c;
}
link text