Objective-C: Comparing string with if() values doesnt work on [NSMutableArray objectatindex:]

29,022

Solution 1

You can't compare strings with == and !=. Technically, that will just compare the pointers and not the values, which is what you want to do.

Instead you want something like:

if (! [yakitVal isEqualToString:@"LPG"]) {

Solution 2

Try using

if (![yakitVal isEqualToString:@"LPG"])
{
...
}

to compare the string values, not == or !=.

EDIT: Negated the conditional.

Solution 3

Thank you guys for the answers, program is finally running as i wanted.

i also realized that my yakitval had a new line char at the end of it. so i've added this like to work

yakitVal = [yakitVal stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
Share:
29,022

Related videos on Youtube

Author by

dreampowder

a Java and Open Source lover. Share the knowledge.

Updated on May 15, 2022

Comments

  • dreampowder 22 minutes

    i've populated a NSMutableArray with NSMutableString Values in my program using NSXML Parser.

    i can succesfully fetch results from the array with objectatindex method, but when i try to compoare that value in an if() structure, it doesnt work, but NSLog shows it has returned the correct value. heres my code and output on Log Window:

     int Total = 0;
     int Adet = 0;
     int LPGvolume = 0;
     for(int i = 0;i<[yakitArray count];i++)
     {
         NSMutableString *yakitVal = [NSMutableString stringWithFormat:@"%@",[yakitArray objectAtIndex:i]];
         NSLog(@"Yakitval: %@",yakitVal);
         if(yakitVal != @"LPG")
         {
             NSMutableString *volumeVal = [volumeArray objectAtIndex:i];
             Total = Total + [volumeVal integerValue];
         }
         else
         {
             NSLog(@"LPG Found!");
             NSMutableString *volumeVal = [volumeArray objectAtIndex:i];
             LPGvolume = [volumeVal integerValue];
         }
         NSMutableString *adetVal = [adetArray objectAtIndex:i];
         Adet = Adet + [adetVal integerValue];
    }
    

    And Heres the Console Output:

    2011-01-10 16:58:10.885 iStationTouch3[39393:7907] Yakitval: Value1
    2011-01-10 16:58:10.886 iStationTouch3[39393:7907] Yakitval: Value2
    2011-01-10 16:58:10.886 iStationTouch3[39393:7907] Yakitval: LPG
    2011-01-10 16:58:10.887 iStationTouch3[39393:7907] Yakitval: Value3
    2011-01-10 16:58:10.888 iStationTouch3[39393:7907] Yakitval: Value4
    2011-01-10 16:58:10.889 iStationTouch3[39393:7907] Yakitval: Value5
    

    even i can see that 'yakitVal' value is LPG from the console window, program never gets into the 'Else' section.

    Maybe i am too tired to see that simple solution but im stuck with this. please help!!.