尝试使用URL创建请求的连接。 NSMutableData实例(responseData)也随之被调用。当连接开始接收响应时,将在NSMutableData实例上调用setLength:NSUInteger方法。

-(void)startDataDownloading
{
    NSURLRequest *_request = [NSURLRequest requestWithURL:self.url];
    if (_request) {
        if (!connecton) {
            connecton = [NSURLConnection connectionWithRequest:_request delegate:self];
            if (connecton) {
                responseData = [NSMutableData data];
                [connecton start];
            }
        }
    }
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    [responseData setLength:0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [responseData appendData:data];
}


但是不知何故,它会导致崩溃,并在setLength调用上显示警告。错误指出

“-[__ NSCFDictionary setLength:]:无法识别的选择器已发送到实例0x6a8cf70
2012-11-30 18:00:38.948 RSSReader [8997:f803] *由于未捕获的异常'NSInvalidArgumentException'而终止应用程序,原因:'-[__ NSCFDictionary setLength:]:无法识别的选择器已发送至实例0x6a8cf70'

关于此的任何提示将不胜感激。

#import <Foundation/Foundation.h>
#import "DataParser.h"

@protocol DataConnectionDelegate <NSObject>
//protocol methods
@end
@interface UCDataConnection : NSObject <ModelParser>
@property (nonatomic, strong) NSURL *url;
@property (nonatomic, strong) NSURLConnection *connecton;
@property (strong, nonatomic) NSMutableData *responseData;
@property (nonatomic, assign) id<DataConnectionDelegate> delegate;
-(void)startDataDownloading;
- (id)initWithUrl:(NSURL *)_url andDelegate:(id<DataConnectionDelegate>)_delegate;


这是头文件的一部分。抱歉,迟到了。

最佳答案

很可能您没有正确地保留responseData,因此它被释放了,在上面的示例中,您碰巧最终在同一位置分配了NSDictionary。

如果您使用的是ARC,那么您发布的代码就可以了(除了“ responseData”,它应该有一个下划线前缀,前提是它是一个实例变量)。

如果您使用的是保留释放,则需要在分配responseData时添加一个调用以保留。

更新:根据您的头文件,看起来您是在直接引用实例变量,并使用了保持释放。最好的选择是仅通过属性机制来引用responseData,即在其所有使用之前加上self.前缀。

关于xcode - NSMutableData setLength:NSUInteger使应用程序崩溃,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13645609/

10-09 16:14