I'm new in objective-c, this is my first post. This is 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 I do:
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 put a breakpoint at the start of function myfunction the memory address of myvar is equal to var, but after the assignment the address of myvar is different from the address of var. How can I solve it? thanks in advance!
While the answers given so far are correct. I think a more pertinent question is why you would want to do this.
It looks you want to have a defensive programming style where the return code indicates success or failure.
A more Objective-C like way to do this would be to pass the string and an NSError **
as a parameter and return the string or a nil to indicate failure as described in the Error Handling Programming Guide
So the way to write this would be:
- (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;
}
And to use it:
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]);
}
This is a trivial example, but you can see that you can construct and return far more meaningful information about the error rather than just whether it succeeded or not.
You can also use NSMutableString
.
-(BOOL) myfunction:(NSMutableString *)myvar {
[myvar setString:@"OK!"];
return YES;
}
and change your call site as follows:
NSMutableString *var = [NSMutableString string];
BOOL control = [self myfunction:var];
if(control)
NSLog(@"var is: %@",var);
Syntactically you need to fix your myFunction invocation like so:
BOOL control = [self myfunction:var];
The real problem here is that inside of myFunction you are assigning a string value to a local string variable only, whereas you want to change the underlying string that it points to. This is usually the wrong approach in Obj-C, but you can do it like so:
-(BOOL)myfunction:(NSString **)myvar
{
*myvar = @"OK!";
return YES;
}
NSString *var;
BOOL control = [self myfunction:&var];
if(control)
NSLog(@"var is: %@",var);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With