传出参数

时间:2011-05-16 17:21:38

标签: iphone objective-c out-parameters

我用out参数编写了一个方法:

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

然后我通过了这样的参数:

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

然而,有一个问题。 out参数值未正确设置。任何人都可以帮我正确地做到这一点吗?

2 个答案:

答案 0 :(得分:27)

创建接受指向对象的指针的方法。

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

}

传入对本地对象的引用。

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

答案 1 :(得分:11)

“out参数”根据定义是指向指针的指针。

您的方法应如下所示:

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

取消引用传入的指针以获取实际的对象引用,然后将其分配给任何[receivedMessage substringFromIndex:2]返回。

调用此方法非常简单:

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