IOS stringByReplacingOccurrencesOfString返回null

时间:2012-09-16 16:50:55

标签: ios string exception

我一直在撞墙撞墙,我一定是在遗漏一些东西。在我对base64编码一些加密文本之后调用此代码。在我调用NSLog签名时,签名始终有效。然而,有时其余的工作很好,其他时候removePlus或finalSig返回null。我也在使用Xcode 4.5,ios6和我为项目启用了ARC。我觉得在我想要它之前可能会有一些东西被自动释放,或类似的东西。如果有人有任何想法,任何帮助表示赞赏。

// Get the data out of the context
char *outputBuffer;
long outputLength = BIO_get_mem_data(context, &outputBuffer);

NSMutableString *signature = [[NSMutableString alloc] init];
[signature appendString:[NSMutableString stringWithCString:outputBuffer encoding:NSASCIIStringEncoding]];

NSLog(@"Base64 Pre Encoded: %@", signature);

signature = [[signature stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding] mutableCopy];
NSMutableString *removePlus = [[signature stringByReplacingOccurrencesOfString:@"+" withString:@"%2B"] mutableCopy];
NSString *finalSig = [removePlus stringByReplacingOccurrencesOfString:@"=" withString:@"%3D"];

//now we create the url request portion
NSMutableString *variables = [[NSMutableString alloc] init];

//set the variables we're going
[variables appendString:finalSig];

2 个答案:

答案 0 :(得分:0)

尝试将代码换成以下内容,因为我认为它会准确显示您的问题所在:

// Get the data out of the context
char *outputBuffer;
long outputLength = BIO_get_mem_data(context, &outputBuffer);

outputBuffer[outputLength] = '\0';
if(outputLength != strlen(outputBuffer)) NSLog(@"SOMETHING VERY WRONG");

NSString * signature = [NSString stringWithCString:outputBuffer encoding:NSASCIIStringEncoding]];
NSLog(@"Base64 Pre Encoded: %@", signature);

signature = [[signature stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
NSLog(@"Base64 Post Encoded: %@", signature);

signature = [signature stringByReplacingOccurrencesOfString:@"+" withString:@"%2B"];
NSLog(@"Base64 Remove '+': %@", signature);

signature = [removePlus stringByReplacingOccurrencesOfString:@"=" withString:@"%3D"];
NSLog(@"Base64 Remove '=': %@", signature);

//now we create the url request portion
NSMutableString *variables = [NSMutableString alloc] initWithString:signature];

…

//set the variables we're going
[variables appendString:finalSig];

答案 1 :(得分:0)

原来NSString * signature = [NSString stringWithCString:outputBuffer encoding:NSASCIIStringEncoding]];需要一个空终止的字符串,而我的字符串不是。无论如何,这是创建字符串的更有效方法:

NSData *myRequestData = [ NSData dataWithBytes: [ variables UTF8String ] length: [ variables length ] ];