初始化 NSString 的长度限制
在下面的代码中,我正在寻找一种限制连接字符串长度的方法。假设我只想检索前 100 个字符。但我不想在检索后进行连接处理。有没有办法初始化具有一定长度的 NSString ?
NSError* error = nil;
NSString *connected = [NSString stringWithContentsOfURL:[NSURL URLWithString:@"http://www.somesite.com"] encoding:NSASCIIStringEncoding error:&error];
In the code below, I am looking for a way to limit the length of connected string. Let's say I only want to retrieve the first 100 characters. But I do not want to do the processing connected after retrieving. Is there a way to initialize NSString with certain length?
NSError* error = nil;
NSString *connected = [NSString stringWithContentsOfURL:[NSURL URLWithString:@"http://www.somesite.com"] encoding:NSASCIIStringEncoding error:&error];
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您将必须自己检索数据,而不是使用 NSString 的便捷方法来执行此操作。例如,如果您使用 NSURLConnection 或 ASIHTTPRequest,则可以在收到所需数量的数据后关闭连接。
You're going to have to retrieve the data yourself instead of using NSString's convenience method to do it. If you use, say, NSURLConnection or ASIHTTPRequest you can close the connection when you've received as much data as you want.
您可以使用 NSString 方法来检索前 100 个字符,但无论如何您都会浪费带宽来获取所有数据。那么,当您只需要 100 个字符时,为什么要下载全部内容呢?
因此,要仅获取来自服务器的一部分数据,您需要对 url 响应提供的数据流进行计数。为此,您可以使用
NSURLConnection
-因此您需要将逻辑放入
didReceiveData
中。在这里,您只需要 100 个字符,因此在达到该数字后断开连接。You could use NSString methods to retrieve the first 100 characters but you would have wasted bandwidth anyway to get all the data. So why download all when you want only 100 chars.
So to get only a slice of the data coming off the server, you need count the data stream that the url response gives. For this you could use
NSURLConnection
-So you need to put your logic in
didReceiveData
. For here, you want only 100 chars, so break-off the connection after that number is reached.