0

I am new to Objective-C development and I have already run into the first problem. I am trying to write a function that takes a string as argument and compares that string with other strings. The pseudo code for the function would be the following:

String string2
String string3

function compare_string (String string) {
  if (string == "a specific string" &&
      string == string2 &&
      string == string3) {
        // do something
      }
}

Until now I only have the following:

NSString *string2 = @"Second string";
NSString *string3 = @"Third string";

(void) compare_string: (NSString *) string {

but now I am already stuck because I don't know how to call the input string string inside the function. Should I simply do something like

if (string == string2) { ... }

or is there another way to use function arguments in Objective-C?

1
  • 1
    Just use "string" -- the "formal parameter" -- to refer to the argument. But note that comparing strings with == will only return true if the two strings are in fact the same object (which is also true in C, Java, and many other languages). To compare two strings for equivalence you need to use isEqualToString. Commented Mar 12, 2013 at 16:30

2 Answers 2

3

This will be like this:

-(void)compareString:(NSString *string){
    if ( [string isEqualToString:@"a specific string"] && [string isEqualToString:string2] && [string isEqualToString:string3] ){
        // do something
    }
}

NOTE: str1==str2 will compare the memory address, and isEqualToString: compares the contents of the strings.

Sign up to request clarification or add additional context in comments.

Comments

1

Check out the docs for NSString there are a bunch of methods that do this for you already - so you don't need to make your own string comparison code

An example would look like

if ([string compare:string2] == NSOrderedSame) { ... }

This is handy if you wish to do complex comparisons like case insensitive etc

for simple equality you could just use

if ([string isEqualToString:string2]) { ... }

Edit

I mis read the question - here is an answer that actually relates to what you asked

You need to use the isEqual: methods defined on object for checking equally. == will only check the pointer values.

You could write your method like this

- (void)compareString:(NSString *)string;
{
  if ([@[string, string, string] isEqual:@[ @"a specific string", string1, string2]]) {
    // do stuff
  }
} 

Then later calling it would look like this

[self compareString:@"A string to compare"];

NB
Wrapping it up in arrays reads slightly nicer than comparing them all individually

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.