【问题标题】:Not able to append NSString无法附加 NSString
【发布时间】:2014-04-11 06:29:38
【问题描述】:

我想在连接失败事件时重新执行NSURLRequest。我想为现有的 POST 参数添加一个参数。

代码:

NSMutableString * postParams = [[NSMutableString alloc] initWithData:((NSData *)((NSURLRequest *)connection.originalRequest).HTTPBody) encoding:NSUTF8StringEncoding];

// If post parameters "retry" is not found in HTTP body
if ([postParams rangeOfString:@"retry="].location == NSNotFound)
{
    // Append a string with parameter "retry" with value true.
    [postParams stringByAppendingString:[NSString stringWithFormat:@"&retry=%d", true]];
    NSLog(@"Modified params : %@", postParams);
}

在我记录它的值时修改字符串中的参数后,它没有改变。

如何将 POST 参数添加到现有请求中?

【问题讨论】:

  • 你不能简单地通过强制转换来使字符串可变。试试mutableCopy
  • @Desdenova 我注意到了这一点并尝试了[NSMutableString alloc]...。同样,它不起作用。
  • 这里不需要所有类型转换和mutableCopy 调用。

标签: ios objective-c ios7 nsurlconnection nsurlrequest


【解决方案1】:

问题在于您用于附加字符串的方法。

stringByAppendingString: 复制当前字符串,附加参数并返回结果。它不会修改原始字符串。

在您的情况下,最简单的修改可能就是使用 appendString: NSMutableString 方法。

[postParams appendString:[NSString stringWithFormat:@"&retry=%d", true]];

【讨论】:

  • appendFormat:会更简单、更快、内存效率更高。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-07-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-01
  • 2011-11-02
  • 1970-01-01
相关资源
最近更新 更多