Objective C - Pass by value and pass by reference

Viewed 35716

First of all, sorry for this simple question. But I need to understand what is happening.

I thought the output should be upper case string. But it comes out to be UPPER CASE STRING.

- (void)test
{
     NSString *stringVar = @"UPPER CASE STRING";
     [self changeString:stringVar];
     NSLog(@"value after changed : %@", stringVar);
}

- (void)changeString:(NSString*)string
{
     string = [string lowercaseString];
}

What is happening and how to fix it?

5 Answers

I am referring to above given problem and helping you with the mistake.Find my comments

- (void)test
{
     NSString *stringVar = @"UPPER CASE STRING";
     //StringVar is a pointer to integer class.let us assume the address the stringVar be 0x50 and the value it has be 0x100
     //So 0x100 has the string 

     [self changeString:stringVar];
     //above we are calling the method to lowercase and argument is stringVar
     //As the method is called we pass 0x100 in the argument as this is the memory where the value is kept

     NSLog(@"value after changed : %@", stringVar);
    //Our StringVar still points to 0x100 where the value is in upperString
}

- (void)changeString:(NSString*)string
{
     string = [string lowercaseString];
    // Now operation performed on string returns a new value on suppose location 0x200
   //String parameter passed in argument is assigned the new value.But we never pass values as we pass only location under the hood
   //New parameter passed now points to new memory location 0x200

}

---------------------------------------------------------------------------------
With the new solution
-(void) test
{
     NSString *stringVar = @"UPPER CASE STRING";
     //let 0x50 be stringVar memorylocation pointing to 0x100 with above value
     [self changeString:&stringVar];
     //0x50 is passed in argument
     NSLog(@"value after changed : %@", stringVar);
     //On new location stored in address of stringVar it points to new string value
}

-(void) changeString:(NSString**)string
{
     *string = [*string lowercaseString];
     //0x200 is new memory location received.*string gives the 0x100 location and hence the value
   //LHS is assigned to new location .On LHS you find *string which will be assigned 0x200
   //As string with location 0x50 is value 0x200 which will make it to point new      location where lowercase string exist
}
Related