Pass the NSString variable to the function and change it

I'm new to objective-c, this is my first post. That's my problem:

In my main file, I have a variable: NSString * var; Then I have a function:

-(BOOL) myfunction:(NSString *)myvar {
myvar = @"OK!";
return YES;
}

Now in the main file:

NSString *var;
BOOL control = myfunction:var;
if(control)
  NSLog(@"var is: %@",var);

but the output is "var is:". If I built in debug mode and set a breakpoint at the beginning of the myfunction function, the memory address of myvar is var, but after assignment, the address of myvar is different from the address of var. How can i solve this? thanks in advance!

+3
source share
3 answers

So far, the answers given so far are correct. I think the more relevant question is why you would like to do this.

It looks like you want to have a defensive programming style where the return code indicates success or failure.

Objective-C, , NSError ** ,

, :

- (NSString *)aStringWithError:(NSError **)outError {
    returnString = @"OK";
    if (!returnString) {
        if (outError != NULL) {
            NSString *myErrorDomain = @"com.company.app.errors";
            NSInteger errNo = 1;
            *outError = [[[NSError alloc] initWithDomain:myErrorDomain code:errNo userInfo:nil] autorelease];
        }
    }
    return returnString;
}

:

NSError *error;
NSString *stringVariable = [self aStringWithError:&error];
if (!stringVariable) {
    // The function failed, so it returned nil and the error details are in the error variable
    NSLog(@"Call failed with error: %ld", [error code]);
}

, , , , .

+6

NSMutableString.

-(BOOL) myfunction:(NSMutableString *)myvar {
    [myvar setString:@"OK!"];
    return YES;
}

:

NSMutableString *var = [NSMutableString string];
BOOL control = [self myfunction:var];
if(control)
  NSLog(@"var is: %@",var);
+4

myFunction : BOOL control = [self myfunction:var];

, myFunction , , . Obj-C, :

-(BOOL)myfunction:(NSString **)myvar
{
  *myvar = @"OK!";
  return YES;
}

NSString *var;
BOOL control = [self myfunction:&var];
if(control)
  NSLog(@"var is: %@",var);
+1

Source: https://habr.com/ru/post/1790739/


All Articles