Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Functions in Objective-C

Tags:

objective-c

I am trying to write a function which returns a string created from two input strings;

but when I try the function declaration

   NSString Do_Something(NSString str1, NSString str2)
   {

   }

the compiler gets sick. (Worked fine for a different function with int arguments.)

If I change the input arguments to pointers to strings, in also gets sick.

So how do I pass Objective-C objects into a function?

like image 801
John R Doner Avatar asked Nov 18 '25 21:11

John R Doner


2 Answers

All Objective-C objects being passed to functions must be pointers. Rewriting it like this will fix your compiler error:

NSString *Do_Something(NSString *str1, NSString *str2) { }

Also, please keep in mind that this is a (C-style) function and not an instance method written on an Objective-C object. If you wanted this to actually be a method on an object it would probably look something like this:

NSString *doSomethingWithString1:(NSString *)str1 string2:(NSString *)str2 { }

I say "probably" because you can name it however you want.

like image 171
Marc W Avatar answered Nov 20 '25 11:11

Marc W


Functions are perfectly fine in Objective-C (and in fact earn some of the language's benefits).

See my answer to C function always returns zero to Objective C, where someone was trying what you are and had a problem with the compiler assuming return type. The structure that I set up there is important when you are using functions, just like when you are using objects and methods. Be sure to get your headers right.

To be pedantic, you're using a function definition of:

NSString *DoSomething(NSString *str1, NSString *str2) {
    // Drop the _ in the name for style reasons
}

And you should be declaring it in a .h file like so:

NSString *DoSomething(NSString *str1, NSString *str2);

Just like C.

like image 27
Jed Smith Avatar answered Nov 20 '25 13:11

Jed Smith



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!