开发者

How to handle the exceptions

NSString *stringURL=[[NSString alloc] init];

stringURL=[stringURL stringByAppendingFormat:kSearchBarURL,text.text];

NSString *url = [NSString stringWithString:stringURL];

NSData *data1 = [NSData dataWithContentsOfURL:[NSURL URLWithString:url]];

NSString *responseids = [[NSString alloc] initWithData:data1 encoding:nil];

responseids = [responseids stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"\n\r\t"]];  

SBJsonParser *parser=[SBJsonParser new];

NSData  *data = [parser objectWithString:responseids error:nil];

NSMutableDictionary *searchURL = (NSMutableDictionary*)data;

I coded this i did not handle the exception for my code.

doing json and calling the service url and loading the data.

the application get crashes when my service is too low or no service found.

How to handle the exception for my code here..

Do I use @try @catch. or NSURLConne开发者_运维问答ction for error handling.

Please help me out .

Thanks in advance.


Whenever an API makes use of NSError, you should use this rather than wrapping things up in a try…catch block as NSError is designed exactly for this. I usually reserve @try for things where I am really not able to anticipate what might go wrong. If NSError is in the mix, then you know that there is a potential for a problem that you should be handling gracefully.

More generally, your code has some strange stuff in it. You alloc init an empty NSString and then create a new string by appending a format. Not sure why you don't just use [NSString stringWithFormat]. Once you have the string, you can create the URL without the NSString *url bit.

You're also using a synchronous call to what I assume is a remote server. This has the potential to bog down your application if/when the server is not available. You're also not telling NSString what kind of encoding you expect your string to be in when it reads it from NSData. A better method depending on your server side would be to use NSString's stringWithContentsOfURL:usedEncoding:error: method. I would recommend that you use the various NSURLConnection callbacks. Have a look at the URL Loading System Programming Guide on Using NSURLConnection The NSURLConnection delegate methods are the ones you want to implement to provide this asynchronous processing.

For your trimming, you might be interested in the +whitespaceAndNewlineCharacterSet method on NSCharacterSet.

Finally, for your JSON parsing, you might be interested in the category that the SBJSON code adds to NSString, particularly -JSONValue which will give you the dictionary or array representation (as appropriate) of the NSString when parsed as JSON by SBJSON.

HTH

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜