dohpaz42 dohpaz42 - 4 months ago 5x
iOS Question

Set NSString by reference from another method

I have a method that accepts an NSString by reference, and the idea is that if an error occurs, the string will contain a specific error message; otherwise, it'll be nil.

-(BOOL)doStuffThatCouldProduceAnError:(NSString *)error {
// An error occurred, so set the string
error = @"Foo Bar is invalid"
return NO;

But the problem is, the caller of
doesn't see the error message:

-(void)someMethod {
NSString *error;
[self doStuffThatCouldProduceAnError:error];
[NSLog @"Message: %@", error]; // Logs "[nil]"

I'm not sure how to search for a solution, and what I did try to search on doesn't cover the passing by reference and setting from another method. I've also tried NSMutableString, but that doesn't seem to make any difference.

Thank you in advance!

Edit: I forgot to mention that I've tried using
error = [error stringByAppendingString:...]
, but that didn't work either.


You are not passing by reference.

You got to do

-(BOOL)doStuffThatCouldProduceAnError:(NSString **)error {
    *error = @"Foo Bar is invalid"


[self doStuffThatCouldProduceAnError:&error];