I have found a strange as for me way to declare a method in Objective C.
Method declaration in .h file:
-(void)methodName:(NSString *)str, int i;
Method implementation in .m file:
-(void)methodName:(NSString *)str, int i
{
NSLog(@"str = %@, int = %d", str, i);
}
I can call this method like this:
[self methodName:@"stringExample", 99];
And it would work fine.
My question is when should I use such syntax. Is there any difference between it and usual declaration?
Objective-C is a very different language with regards to its syntax. It's so different, even, that most people don't look at it long enough to realize that the semantics of the language are almost identical to C++, Java, or others.
Objective-C uses the runtime code compilation Objective-C isn't a fast language. The main reason is that it uses the runtime code compilation, rather than the compile time. This means that when the Objective-C object calls for another object in the code, there is an extra level of indirection involved.
In Objective-C, any character , numeric or boolean literal prefixed with the '@' character will evaluate to a pointer to an NSNumber object (In this case), initialized with that value. C's type suffixes may be used to control the size of numeric literals. '@' is used a lot in the objective-C world.
Objective-C is a not a difficult language, and once you spend some time with it you'll find it elegant as well : r/iOSProgramming.
As described here, those parameters are optional:
Methods that take a variable number of parameters are also possible, though they’re somewhat rare. Extra parameters are separated by commas after the end of the method name. (Unlike colons, the commas are not considered part of the name.) In the following example, the imaginary makeGroup: method is passed one required parameter (group) and three parameters that are optional:
[receiver makeGroup:group, memberOne, memberTwo, memberThree];
So yes, the declaration is different to the usual declaration. I cannot find any regular use of this type of declaration other than with a varargs method, where the optional parameter is declared as ...
.
The aim in declaring methods like: -(void)methodName:(NSString *)str yourInt:( int) i{...}
is for making it more readable. After llvm 4.0 declaring strings, arrays, dictionaries .. can be handled like other C languages.. For instance, the both of declarations below are true:
//old style
array = [nsarray arraywithobjects:a, b, c, nil];
dict = [nsdictionary dictionarywithobjects:@[o1, o2, o3]
forkeys:@[k1, k2, k3]];
number = [nsnumber numberwithchar:'x'];
number = [nsnumber numberwithint:12345];
//new style
array = @[ a, b, c ];
dict = @{ k1 : o1, k2 : o2, k3 : o3 };
number = @'x';
number = @12345;
Resource from a Turkish forum is here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With