objective-ciosheadercrashnshttpurlresponse

NSHTTPURLResponse's initWithURL method crashes if we set header "Content-Length"


Here's some code, where we set up an NSHTTPURLResponse object:

NSString * data = @"response successful";
NSUInteger length = [data length];
NSDictionary * headersDict = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithUnsignedInt:length], @"Content-Length", nil];

NSHTTPURLResponse * response = [[NSHTTPURLResponse alloc] initWithURL:[request URL] statusCode:200 HTTPVersion:@"1.1" headerFields:headersDict];

The following code will crash at the last line if we put headersDict as parameter.

error: testReportAppOpenToAdMobWithAppstoreId (AdTrackerTests) failed: -[__NSCFNumber length]: unrecognized selector sent to instance 0xf653f40

I don't know why it crashes. Debugging shows that headersDict is good, I suspect a bug on Apple's part.

Any ideas?


Solution

  • NSHTTPURLResponse is probably expecting an NSString, not an NSNumber. Try converting the length value to an NSString.