Alex Rivera | Logout

Arguments by reference in Objective-C

Asked 2010-07-26T01:49:20.487
21

I'm trying to pass an NSString by reference but it doesn't work.

This is the function:

+(void)fileName:(NSString *) file
{
    file = @"folder_b";
}

and this is the call:

NSString *file;

[function fileName:file];

nslog(@"%@",file);    // and there is nothing in the string....

What I must do to pass my string by reference?

Edit
Report

1 Answer

32

I believe you're looking for:

+ (void)fileName:(NSString **)file
{
  *file = @"folder_b";
}

What's really done here is we're working with a pointer to a pointer to an object. Check C (yup, just plain C) guides for "pointer dereference" for further info.

(...But as has been pointed out repeatedly, in this particular example, there's no reason to pass by reference at all: just return a value.)

answered 2010-07-26T01:56:06.780

Your Answer