开发者

Objective-C NSURLConnection

Can I put all connection related functions into it's own 开发者_JS百科(singleton?) class or possibly the app delegate?

I've got a lot of code repetition right now...

eg. this method is in at least 5 files:

- (void)connection:(NSURLConnection*)connection didFailWithError:(NSError*)error;

Would I just import a class with these methods in it? Do I have to extend or whatever to use them?


I wouldn't recommend a singleton approach for a NSURLConnection handler, mainly because each url connection is different and may need to be handled differently.

It may seem like you have a lot of code repetition if you have simple requests, but as you start to make more complex requests, and parsing the different responses you get back from the requests, you'll soon start to see that a generic approach won't save you from having to write more specific implementations.


The right answer really depends on how complex your network interaction is. If it is complex and you try to do it all in one class then you will end up with endless cases in every method in the class. If it is simple enough to do in one class I don't think you need to make it a singleton. Because of the way the NSURLConnection delegate functions work you probably don't even need to have the connection object as an ivar.

One strategy is to define an interface that you will use to get information in a parent class called DataSource or similar. All of your classes that send or consume data are written to use that interface. During development you can use a subclass called FileSource, and get dummy data you have locally. Later you switch to the NetSource subclass which actually goes and does the fetch using the net. You can do the switch using something as simple as changing a file: URL scheme for a http: scheme - and the DataSource class can have a class method which interprets the URL and tells you which kind of class to instantiate, so you can switch between using just a .plist setting.


I have a class, that takes care of downloading requests and is being autoreleased in the end of taking care of data. It's not a singleton, rather an object, that I initialize with an url each time i need to launch the NSURLConnection. This class has a delegate for taking care of received data.

Hope this helps

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜