2

just a small question with a simple and short answer I hope ;-)

What exactly is the difference between (i.e.)

NSData *htmlData = [NSURLConnection sendSynchronousRequest:self.request returningResponse:&response error:nil];

and

NSData *htmlData = [NSData dataWithData:[NSURLConnection sendSynchronousRequest:self.request returningResponse:&response error:nil]]

Or isn't there any difference at all? If it matters, yes I use ARC.

Thanks a lot!

4

1 回答 1

2

There is not a simple and short answer :)

In the first, you handle the data returned from the URL connection.

In the second, you create a copy of that data -- that 'copy' btw, may not actually be a deep copy for a number of reasons.

How this performs can actually go both ways, and a lot of it is hard to answer because:

  • a) it depends largely on how your program uses that data and
  • b) internal optimizations and implementation details of the APIs you're using
  • c) copy or retain semantics of your objects

Personally, I prefer the latter when I need to pass that data around. The reason is that you should declare your ivars for types which have mutable variants as copy (NSMutableData in this case), and you should generally work with immutable copies of these objects where possible. Once much of your implementations handle these types with mutable variants by copy, then you can actually reduce copying by ensuring the objects you deal with are in fact immutable -- immutable objects can avoid deep and even shallow copies when a copy is requested.

If that data is passed nowhere else, then you could avoid a potential copy in the event the API returns an instance of NSMutableData (i.e. you can use the first safely).

于 2012-10-17T16:03:08.100 回答