19

I wrote a method with an out parameter:

-(NSString *)messageDecryption:(NSString *)receivedMessage outParam:(out)messageCondent
{   
    messageCondent = [receivedMessage substringFromIndex:2];
    return [receivedMessage substringToIndex:1];
}

Then I passed the param like this:

NSString *messageCondent;
NSString *mode = [myclassobject messageDecryption:message outParam:messageCondent];

However, there is a problem. The out parameter value is not being set properly. Can any one help me to do this correctly?

i_am_jorf
  • 53,608
  • 15
  • 131
  • 222
Vipin
  • 4,718
  • 12
  • 54
  • 81
  • Shouldn't you specify a type? outParam:(out NSString *)? – peterp May 16 '11 at 17:27
  • 1
    I've never actually seen this `out` method used before. I think most people simply implement value by reference. (Check the correct answer on this page: https://discussions.apple.com/thread/1502936?threadID=1502936) – peterp May 16 '11 at 17:28
  • 2
    Take into consideration that [pass by reference in Cocoa/iOS is largely limited to `NSError**`](http://stackoverflow.com/questions/3331791/arguments-by-reference-in-objective-c/3332062#3332062). If you need to return more than one value at a time, that begs for a structure or, more often, a class. – albertamg May 16 '11 at 17:36
  • 1
    `out` is a keyword in Objective-C that was related to Distributed Objects. It isn't used much anymore. – bbum May 16 '11 at 19:56

2 Answers2

28

Create the method to accept a pointer to the object.

-(NSString *)messageDecryption:(NSString *)receivedMessage outParam:(NSString**)messageCondent
{   
    *messageCondent = [receivedMessage substringFromIndex:2];
    return [receivedMessage substringToIndex:1];

}

Pass in the reference to the local object.

NSString *messageCondent = nil;
NSString *mode = [myclassobject messageDecryption:message outParam:&messageCondent];
tidwall
  • 6,881
  • 2
  • 36
  • 47
11

An "out parameter" is by definition a pointer to a pointer.

Your method should look like this:

-(NSString *)messageDecryption:(NSString *)receivedMessage outParam:(NSString **)messageCondent
{   
    *messageCondent = [receivedMessage substringFromIndex:2];
    return [receivedMessage substringToIndex:1];
}

This dereferences the passed-in pointer to get at the actual object reference and then assigns that to whatever [receivedMessage substringFromIndex:2] returns.

Invoking this method is quite simple:

NSString *messageCondent = nil;
NSString *mode = [myclassobject messageDecryption:message outParam:&messageCondent];
Jacob Relkin
  • 161,348
  • 33
  • 346
  • 320
  • No, an "out parameter" is a pointer to a *value*. That the value is a pointer is only true if the value is an object. But it could just as well be an `int` – Thomas Tempelmann Sep 04 '20 at 10:04