Passing variables to a function
My lingo is so Actionscript, but that is changing slowly. Variables are methods, and we’re actually passing properties in Objective-C. But ok. Yesterday I wrote about declaring and calling functions/methods in Objective-C. Now I’ll try to explain how to declare functions that accept variables and how to pass variables to them. Also I cover briefly how to get ‘trace’ statements in Objective C.
So let’s cut to the chase.
Trace Statements
Actionscript:
var string:String = "I AM STRING";
trace("I am getting traced in the console ");
trace("I am a variable: "+string);
Objective-C
NSString *string = @"I AM STRING"; NSLog(@"I am getting traced in the console"); NSLog(@"I am a variable %@",string);
Now note how variables work in NSLog statements. characters starting with % sign will get substituted by comma separated variables. Also all string defined have to have “@” in front of them.
They’re a bit to get used to. I will pass a cheatsheet of different variables
Actionscript
private function myFunction(foo:String){
trace("I got the variable "+foo);
}
Passing a variable to a function
Passing a var to a function in Actionscript:
private firstFunction():void{
var str:String = "This is passed data";
anotherFunction(str);
}
private anotherFunction(s:String):void{
trace(s); //Output: This is passed data
}
Passing a variable to a function with Objective-C:
//First add this line to your header (.h) file;
- (void)anotherFunction:(NSString *)s;
//then in Class file (.m) you can call this function like so:
-(void)firstFunction{
NSString *str = @"This is passed data";
[self anotherFunction:str];
}
- (void)anotherFunction:(NSString *)s{
NSLog(@"%@",s); //Output This is passed data
}
Make sure ‘firstFunction’ is called. Try to use AppDelegate’s initWithOptions as your firstFunction.
Objective C NSLog cheatsheet:
%@ Object %d, %i signed int %u unsigned int %f float/double %x, %X hexadecimal int %o octal int %zu size_t %p pointer %e float/double (in scientific notation) %g float/double (as %f or %e, depending on value) %s C string (bytes) %S C string (unichar) %.*s Pascal string (requires two arguments, pass pstr[0] as the first, pstr+1 as the second) %c character %C unichar %lld long long %llu unsigned long long %Lf long doubleTags: actionscript, flash, javascript, learning, objc, objective c