12

I was wondering what the difference between setting a header value and adding a header value to an NSMutableURLRequest is. Sounds sort of obvious but, for example, can't you just use addValue every time? Will setting a header that doesn't exist throw an error? Will adding a header when it already exists in the request overwrite the existing value?

example

let request.NSMutableURLRequest(URL: NSURL(string: "someURL")!) 
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
...
Danoram
  • 8,132
  • 12
  • 51
  • 71

1 Answers1

25

I think the discussion in Apple's official doc is quite clear:

addValue

This method provides the ability to add values to header fields incrementally. If a value was previously set for the specified field, the supplied value is appended to the existing value using the appropriate field delimiter. In the case of HTTP, the delimiter is a comma.

setValue

The new value for the header field. Any existing value for the field is replaced by the new value.


setValue replaces. addValue appends with a delimiter

mfaani
  • 33,269
  • 19
  • 164
  • 293
ljk321
  • 16,242
  • 7
  • 48
  • 60
  • Oh wow ok this has clarified my understanding hugely! unless appending values to current headers I should use set value? In my mind 'addValue' seemed like another term for 'add a header'.. – Danoram Apr 23 '15 at 06:51
  • 2
    @Danoram Depends on what you are trying to accomplish. I feel that setValue is enough for most circumstances. – ljk321 Apr 23 '15 at 10:12
  • What if we "setValue" for non existing key? Will crash with unknown key exception I guess! – byJeevan Nov 17 '16 at 11:56
  • No, App won't crash if we put setValue which has not exist but there will no impact to request and response at all. I think setValue should use always. Because when we use header field means already they are defined inside database. – Arun Kumar Jun 06 '19 at 12:19