Thursday 16 April 2015

What is Error *error, Error **error and &error?

Let us consider below code, here we are passing a NSString pointer to pointer object. Which is same as call by reference in C language. But in Objective C we are taking every Object as reference type so taking pointer of an pointer object we need to write it as NSString **, not like NSString *.

In simple word if you understand the below code as Call by reference and call by value concept in Objective C. You can easily find out that why most of the methods are defined as Error **error instead of Error *error. We all know that In C and Objective C method can return only single value as return type. So put value in Error we need a pointer of Error.
Therefore in Objective C we passing Error ** as &error. It is all syntactical thing related to Objective C. Concept is the same as C language calling by reference and value.
Voila for reading this

-(void)changePointerOfString:(NSString **)strVal {
        *strVal = @"New Value";
}

-(void)changeOfString:(NSString *)strVal {
        strVal = @"New Value";
}


-(void)caller {
        NSString *myStr = @"Old Value";
        // myStr has value 'Old Value'
        NSLog(@"%@", myStr);

       [self changeOfString:myStr];
       // myStr has value 'Old Value'
       NSLog(@"%@", myStr);
       
       [self changePointerOfString:&myStr];
       // myStr has value 'New Value'
       NSLog(@"%@", myStr);
}

No comments:

Post a Comment