cfstring length message sent to deallocated instance? - iphone

I m doing the concept of autocomplete feature for a textField and in doing so I m getting the following error:
"cfstring length message sent to deallocated instance"
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
if( textField == txtcity)
{
autocompleteTableView.hidden = NO;
NSString *substring = [NSString stringWithString:textField.text];
substring = [substring stringByReplacingCharactersInRange:range withString:string];
[self searchAutocompleteEntriesWithSubstring:substring];
return YES;
}
}
- (void)searchAutocompleteEntriesWithSubstring:(NSString *)substring {
subString2=[NSString stringWithFormat:#"%#",substring];
NSMutableData *data = [[NSMutableData alloc] init];
self.receivedData = data;
[data release];
NSURL *jsonUrl =[NSURL URLWithString:[NSString stringWithFormat:#"http://210.90.32.122/services/AutoService.svc/GetCities/?p=%#&k=%#",substring,txtId.text]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:jsonUrl];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request
delegate:self];
self.connection = connection;
[connection start];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[receivedData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[receivedData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
parser = [[NSXMLParser alloc] initWithData:receivedData];
[parser setDelegate:self];
[parser setShouldProcessNamespaces:NO];
[parser setShouldReportNamespacePrefixes:NO];
[parser setShouldResolveExternalEntities:NO];
[parser parse];
[parser release];
NSLog(#"%#",arr2);
if([arr2 count]!=0)
{
self.autocompleteUrls = [[NSMutableArray alloc] init];
if(autocompleteTableView)
[autocompleteTableView removeFromSuperview];
autocompleteTableView = [[UITableView alloc] initWithFrame:CGRectMake(88, 428, 200,[arr2 count]*20) style:UITableViewStyleGrouped];
autocompleteTableView.delegate = self;
autocompleteTableView.dataSource = self;
autocompleteTableView.scrollEnabled = YES;
autocompleteTableView.rowHeight=20;
[self.view addSubview:autocompleteTableView];
for(int i=0;i<[arr2 count];i++)
{
NSString *curString = [[arr2 objectAtIndex:i] valueForKey:#"Name"];
NSRange substringRange = [curString rangeOfString:subString2]; //error at this line
if (substringRange.location == 0)
[autocompleteUrls addObject:curString];
}
}
[autocompleteTableView reloadData];
txtcity.text=subString2;
[txtcity resignFirstResponder];
}
my subString2 is becoming null.But I have retained it while decalring
#property(nonatomic,retain)NSString *subString2;
Where Im going wrong.Couldn't understand where it is being deallocated..

You're not actually retain it. You're setting the object variable subString2 not though the property, that is the reason. Try this:
self.subString2 = [NSString stringWithFormat:#"%#",substring];
But it is not very good practise to get to the object variables from the object through the properties. There is two options:
[subString2 release];
subString2 = [[NSString stringWithFormat:#"%#",substring] copy];
OR
[subString2 release];
subString2 = [[NSString stringWithFormat:#"%#",substring] retain];

Related

About how to use NSThread

I'm an iPhone developer.
I studied about how to use NSThread. So I created source code.
But, I'm not sure about my source code whether good or bad.
-(void)check_threadEnd
{
if ([_thread isFinished]) {
threadCount++;
if (threadCount == 4) {
[self performSelector:#selector(removeActivityView) withObject:nil afterDelay:0.0];
[self.tableView reloadData];
}
}
}
Sometimes, threadCount doesn't become 4.
So, ActiveView is worked continual without stopping.
Turn the timer after a period of time, remove ActiveView?
I'll give you some advice please.
-(IBAction)click_ServerSync:(id)sender
{
if ([util checkNetwork]) {
threadCount = 0 ;
[self displayActivityView];
NSOperationQueue *queue = [[[NSOperationQueue alloc] init] autorelease];
[queue setMaxConcurrentOperationCount:4];
_thread = [[NSThread alloc] initWithTarget:self selector:#selector(_th) object:nil];
[_thread start];
}
}
-(void)_th
{
[self performSelectorOnMainThread:#selector(LoadXml:) withObject:#"XML1" waitUntilDone:NO];
[self performSelectorOnMainThread:#selector(LoadXml:) withObject:#"XML2" waitUntilDone:NO];
[self performSelectorOnMainThread:#selector(LoadXml:) withObject:#"XML3" waitUntilDone:NO];
[self performSelectorOnMainThread:#selector(LoadXml:) withObject:#"XML4" waitUntilDone:NO];
}
-(void)LoadXml:(NSString*)P_VAL
{
NSString *smsURL = [NSString stringWithFormat:#"%#%#.asp", XML_URL, P_VAL];
NSString *sendAuthInfo = [NSString stringWithFormat:#"A=%#&B=%d&C=%#&D=%#" , A, B, C, D ];
NSString *val = [sendAuthInfo stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:smsURL]]autorelease];
[request setURL:[NSURL URLWithString:smsURL]];
[request setHTTPMethod:#"POST"];
[request setHTTPBody: [val dataUsingEncoding: NSUTF8StringEncoding]];
[self startAsyncLoad:request tag:P_VAL];
}
- (void)startAsyncLoad:(NSMutableURLRequest*)request tag:(NSString*)tag {
CustomURLConnection *connection = [[CustomURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES tag:tag];
if (connection) {
[receivedData setObject:[[NSMutableData data] retain] forKey:connection.tag];
}
}
- (NSMutableData*)dataForConnection:(CustomURLConnection*)connection {
NSMutableData *data = [receivedData objectForKey:connection.tag];
return data;
}
-(void)check_threadEnd
{
if ([_thread isFinished]) {
threadCount++;
if (threadCount == 4) {
[self performSelector:#selector(removeActivityView) withObject:nil afterDelay:0.0];
[self.tableView reloadData];
}
}
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
NSMutableData *dataForConnection = [self dataForConnection:(CustomURLConnection*)connection];
[dataForConnection setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
NSMutableData *dataForConnection = [self dataForConnection:(CustomURLConnection*)connection];
[dataForConnection appendData:data];
}
-(void)connectionDidFinishLoading:(NSURLConnection*)connection
{
NSLog(#" connection connectionDidFinishLoading : %d", [connection retainCount]);
NSMutableData *dataForConnection = [self dataForConnection:(CustomURLConnection*)connection];
[connection release];
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
NSXMLParser *xmlParser = [[[NSXMLParser alloc] initWithData:dataForConnection] autorelease];
XMLParser *parser = [[XMLParser alloc] initXMLParser];
[xmlParser setDelegate:(id)parser];
parser.viewDelegate = (id)self;
[xmlParser parse]; // xml parser
}
Do you have a reason as to why you are opting for NSThread over NSOperation? NSOperation abstracts away a lot of the lower-level thing you would have to worry about with NSThread. I would strongly recommend you read up on this concurrency programming guide from Apple.
Pay attention to the last section, Migrating Away From Threads, as it talks about additional alternatives that can help you write robust, clean code.

Crash on [responseData setLength:0];

I am making a async request and I'm getting a EXC_BAD_ACCESS on [responseData setLength:0];
The Code is:
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[responseData setLength:0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[responseData appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog(#"Connection failed: %#", [error description]);
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
[responseData release];
luckyNumbers1 = [responseString JSONValue];
NSUserDefaults *information = [NSUserDefaults standardUserDefaults];
/*NSArray *luckyNumbers = [json objectWithString:responseString error:&error];*/
NSLog(#"luckyNumbers1: %#", luckyNumbers1);
NSLog(#"user Info array is: %#", luckyNumbers1);
// [information setObject:[NSString stringWithFormat:#"%#", (NSString *)[luckyNumbers1 objectForKey:#"session"]] forKey:#"sessionID"];
NSDictionary *array = (NSDictionary *)[luckyNumbers1 objectForKey:#"data"];
NSEnumerator *inner = [luckyNumbers1 objectEnumerator];
id value;
while((value = [inner nextObject])) {
NSLog(#"user Info array is: %#", value);
if ( [value isKindOfClass:[NSDictionary class]] ) {
[information setObject:[value objectForKey:#"id"] forKey:#"userID"];
NSLog(#"uid is: %#", [value objectForKey:#"id"]);
[information setObject:[NSString stringWithFormat:#"%#", (NSString *)[value objectForKey:#"points_all"]] forKey:#"pointString"];
[information setObject:[NSString stringWithFormat:#"%#", (NSString *)[[[value objectForKey:#"leaderboards"] objectForKey:#"all"] objectForKey:#"position"]] forKey:#"rankString"];
if ((NSNull *)[value objectForKey:#"display_name"] == [NSNull null]) {
[information setObject:#"No Display Name" forKey:#"displayNameString"];
} else {
[information setObject:[NSString stringWithFormat:#"%#", (NSString *)[value objectForKey:#"display_name"]] forKey:#"displayNameString"];
}
if ((NSNull *)[value objectForKey:#"level"] == [NSNull null]) {} else {
[information setObject:[NSString stringWithFormat:#"%#", (NSString *)[[[value objectForKey:#"level"] objectForKey:#"definition"] objectForKey:#"name"]] forKey:#"levelString"];
}
pointsTV = [[UILabel alloc] initWithFrame:CGRectMake(222, 294, 441, 22)];
pointsTV.text = [NSString stringWithFormat:#"Points: %#", [information stringForKey:#"pointString"]];
pointsTV.backgroundColor = [UIColor clearColor];
pointsTV.textColor = [UIColor whiteColor];
[TVWindow addSubview:pointsTV];
rankLabelTV = [[UILabel alloc] initWithFrame:CGRectMake(222, 269, 441, 22)];
rankLabelTV.backgroundColor = [UIColor clearColor];
rankLabelTV.textColor = [UIColor whiteColor];
rankLabelTV.text = [NSString stringWithFormat:#"Rank: %#", (NSString *)[[[array objectForKey:#"leaderboards"] objectForKey:#"all"] objectForKey:#"position"]];
[TVWindow addSubview:rankLabelTV];
levelNameLabelTV = [[UILabel alloc] initWithFrame:CGRectMake(222, 244, 441, 22)];
levelNameLabelTV.backgroundColor = [UIColor clearColor];
levelNameLabelTV.textColor = [UIColor whiteColor];
if ((NSNull *)[value objectForKey:#"level"] == [NSNull null]) {
levelNameLabelTV.text = #"No Level";
} else {
levelNameLabelTV.text = [NSString stringWithFormat:#"Level: %#", (NSString *)[[[array objectForKey:#"level"] objectForKey:#"definition"] objectForKey:#"name"]];
}
[TVWindow addSubview:levelNameLabelTV];
pointLabel.text = [information stringForKey:#"pointString"];
pointLabel.textAlignment = UITextAlignmentLeft;
displayNameLabelTV.text = [information stringForKey:#"displayNameString"];
displayNameLabel. text = [information stringForKey:#"displayNameString"];
rankLabel.text = [information stringForKey:#"rankString"];
levelLabel.text = [information stringForKey:#"levelString"];
NSURL *url1 = [NSURL URLWithString: [NSString stringWithFormat:#"%#", (NSString *)[array objectForKey:#"picture_url"]]];
NSData *urlData1 = [NSData dataWithContentsOfURL:url1];
UIImage *image1 = [UIImage imageWithData:urlData1];
profilePicture.image = image1;
profilePictureTV.image = image1;
[information setObject:[NSString stringWithFormat:#"%#", (NSString *)[luckyNumbers1 objectForKey:#"session"]] forKey:#"sessionID"];
}}
NSURLRequest *request2;
request2 = [NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:#"http://%#/api/widgets/%#/%#/players/%#/rewards.json", [information stringForKey:#"host"], [information objectForKey:#"apiKey"], [information objectForKey:#"URL"], [information objectForKey:#"userID"]]]];
NSLog(#"Badges Request is: %#", request2);
NSURLConnection *connection2;
connection2 = [[NSURLConnection alloc] initWithRequest:request2 delegate:self startImmediately:YES];
NSURLResponse *resp3;
NSData *cData2 = [NSURLConnection sendSynchronousRequest:request2 returningResponse:&resp3 error:nil];
NSString *cDataString2 = [[NSString alloc] initWithData:cData2 encoding:NSUTF8StringEncoding];
[self getUsersBadges: cDataString2];
[[NSURLConnection alloc] initWithRequest:request2 delegate:self];
// pass cDataString into the JSON parser and update points
[connection release];
}
Without seeing your initialization of reponseData, it’s hard to be sure, but I would guess that you’re either declaring it as [NSMutableData data] (which will get autoreleased) or release/autoreleaseing it before you get to -connection:didReceiveResponse:. The solution is to make sure it doesn’t get released early, either by calling retain on it or by initializing it with [[NSMutableData alloc] init]. In either case, you’ll need to release it once you’re done, though it looks as if you’re doing that already in your -connectionDidFinishLoading:, so no change needed there.

Need to call retain for a property with retain flag specified

I'm newbie in Objective-C, and as most of the newbies I have a questions about references management.
I've written a class which downloads data using NSURLConnection. The code is similar to Apple's example in http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/URLLoadingSystem/Tasks/UsingNSURLConnection.html. The only difference is that receivedData variable is declared as "#property (nonatomic,retain) NSMutableData *receivedData;" In .m file I have "#synthesize receivedData = _receivedData;".
I have connectionStart function which starts downloading data. In this function I have this code:
if (theConnection) {
// Create the NSMutableData to hold the received data.
// receivedData is an instance variable declared elsewhere.
self.receivedData = [NSMutableData data];
} else {
// Inform the user that the connection failed.
}
The program crashes with this message:
2011-06-12 12:47:22.298 WebGallery[1212:207] *** -[NSConcreteMutableData release]: message sent to deallocated instance 0x118a6fe0
If I change receivedData assignment to this code:
self.receivedData = [[NSMutableData data] retain];
Then the program works correctly and no memory leaks are detected.
As you see I need to call retain on NSMutableData and I'm using property, which is declared as "retain".
Why does this happen?
EDIT: Full contents of .m file:
#import "GalleryData.h"
#import "XmlParser.h"
#implementation GalleryData
#synthesize receivedData = _receivedData;
#synthesize imagesData = _imagesData;
#synthesize delegate = _delegate;
#synthesize currentObjectType = _currentObjectType;
#synthesize currentObjectIndex = _currentObjectIndex;
- (id) init
{
[super init];
_imagesData = [[NSMutableArray alloc] init];
return self;
}
- (void) dealloc
{
[_imagesData release];
_imagesData = nil;
[super dealloc];
}
- (void) connectionStart:(NSURL *)theURL
{
NSURLRequest *theRequest = [NSURLRequest requestWithURL:theURL cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if (theConnection) {
// Create the NSMutableData to hold the received data.
// receivedData is an instance variable declared elsewhere.
//ASK: Kodėl čia reikia daryti retain jei #property jau nustatyta retain?
self.receivedData = [[NSMutableData data] retain];
} else {
// Inform the user that the connection failed.
}
}
- (void) startLoading
{
NSLog(#"Loading started");
self.currentObjectIndex = 0;
self.currentObjectType = ObjectTypeXML;
[self connectionStart:[NSURL URLWithString:#"http://www.aleksandr.lt/gallery/data.xml"]];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[self.receivedData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[self.receivedData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
[connection release];
[self.receivedData release];
NSLog(#"Connection failed! Error - %# %#",
[error localizedDescription],
[[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[connection release];
if (self.currentObjectType == ObjectTypeXML) {
NSXMLParser *nsXmlParser = [[NSXMLParser alloc] initWithData:self.receivedData];
XmlParser *parser = [[XmlParser alloc] initXmlParser:self.imagesData];
[nsXmlParser setDelegate:parser];
[nsXmlParser parse];
[nsXmlParser release];
[parser release];
[self.receivedData release];
self.receivedData = nil;
if ([self.imagesData count]) {
self.currentObjectIndex = 0;
self.currentObjectType = ObjectTypeThumbImage;
ImageData *firstImage = [self.imagesData objectAtIndex:0];
NSURL *theURL = [NSURL URLWithString:firstImage.thumbImageURL];
[self connectionStart:theURL];
} else {
[self.delegate loadingFinished];
return;
}
} else if (self.currentObjectType == ObjectTypeThumbImage) {
ImageData *currentImage;
currentImage = [self.imagesData objectAtIndex:self.currentObjectIndex];
UIImage *thumbImage = [[UIImage alloc] initWithData:self.receivedData];
if (thumbImage == nil) {
NSLog(#"image was not created");
}
[currentImage setThumbImageScaled:thumbImage];
[thumbImage release];
[self.receivedData release];
self.receivedData = nil;
if (self.currentObjectIndex == ([self.imagesData count] - 1)) {
[self.delegate loadingFinished];
return;
}
self.currentObjectIndex++;
currentImage = [self.imagesData objectAtIndex:self.currentObjectIndex];
NSLog(#"'%#'", currentImage.thumbImageURL);
NSURL *theURL = [NSURL URLWithString:currentImage.thumbImageURL];
[self connectionStart:theURL];
}
}
#end
Do not call [self.receivedData release] - this leaves the internal pointer dangling. The whole point of a retained property is that it releases itself. Just do self.receivedData = nil.
Here is your problem:
[self.receivedData release];
self.receivedData = nil;
You're releasing the attribute twice (first time explicitly and second time implicitly by assigning nil).

Adding a new row in a UITableView

HI Everyone,
It is my first post here and this is my problem:
I am trying to get some data from a REST API call and show then in a UITableView.
This s what I am doing:
in the viewDidLoad: 1) here I initialize my array of things to show in the Table (that is empty at the beginning) 2) the table is loaded (with 0 rows) and 3) then the HTTP async call is issued.
Done this I do my stuff with the HTTP Response and when ready I call the reloadData on my table. Here the strange happens.
numberOfRowsInSelection returns me the correct number of rows
but
tableView:cellForRowAtIndexPath:indexPath for the indexPath.row always returns me zero!
so no new row is added to the table.
- (void)doJSONRequest{
responseData = [[NSMutableData data] retain];
NSString *addr = [[NSString alloc] initWithFormat:#"http://localhost:8080/blabla/v1/items?count=10"];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:addr]];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
[addr release];
}
- (void)doJSONRequestWithURL:(NSString *)url{
responseData = [[NSMutableData data] retain];
NSString *addr = [[NSString alloc] initWithFormat:url];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:addr]];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
[addr release];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
//NSLog(#"[%#] connection:didReceiveResponse %#",[self class], response);
[responseData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
//NSLog(#"[%#] connection:didReceiveData %#",[self class], data);
[responseData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog(#"[%#]",[NSString stringWithFormat:#"Connection failed: %#", [error description]]);
UIAlertView *alert = [[UIAlertView alloc] init];
[alert setTitle:#"NETWORK ERROR!"];
[alert setMessage:#"App will close"];
[alert setDelegate:self];
[alert addButtonWithTitle:#"Close"];
[alert show];
[alert release];
[alert show];
[alert release];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
//NSLog(#"[%#] connectionDidFinishLoading %#",[self class], connection);
[connection release];
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
[responseData release];
NSDictionary *res = [NSDictionary dictionaryWithDictionary:[responseString JSONValue]];
NSDictionary *tmp = [res valueForKey:#"reviews"];
tmp = [tmp valueForKey:#"reviews"];
NSEnumerator *e = [tmp objectEnumerator];
NSDictionary *tmp_review;
int i=0;
while (tmp_review = [e nextObject]) {
//NSLog(#"tmp_review %#", tmp_review);
//NSLog(#"count %d", i++);
MyObject r = [... doing my staff...]
[reviews addObject: r];
[r release];
};
[reviewListTableView reloadData];
[responseString release];
}
- (void)viewDidLoad {
//- (void)initUI {
//review is the array where I put my data
//it is empty at the beginning
reviews = [[NSMutableArray alloc] initWithObjects:nil];
[super viewDidLoad];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [reviews count]
}
Sounds like you may not have properly implemented numberOfSectionsInTableView:. You should log indexPath.section in tableView:cellForRowAtIndexPath:indexPath to see what section value you are passing. You will have multiple indexPath.row values of zero because there is a zero row for each section.
add new object in the array and [mytableview reloadData];
Implement following data source return number of section to be present in the table view.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView;
In tableView:cellForRowAtIndexPath:indexPath check section number and do your operation.
Note: If you don't need sections you can remove it.

How to parse Google weather API using NSXML?

i want to parse google weather API using NSXML so please give me some Guidance for this.
This is My url
and i have taken such kind of steps:
NSURL *url = [NSURL URLWithString:#"http://www.google.com/ig/api?weather=Ahemdabad"];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
[theRequest setHTTPMethod:#"POST"];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if(theConnection){
webData = [[NSMutableData data] retain];
NSLog( #"connection established");
}
else {
NSLog(#"theConnection is NULL");
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[webData setLength: 0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[webData appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(#"ERROR with theConenction");
[connection release];
[webData release];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connectio
{
NSLog(#"DONE. Received Bytes: %d", [webData length]);
NSString *theXML = [[NSString alloc] initWithBytes: [webData mutableBytes] length:[webData length] encoding:NSUTF8StringEncoding];
NSLog(#"thexml=============>%#", theXML);
[theXML release];
if(parser)
{
[parser release];
}
parser = [[NSXMLParser alloc]initWithData:webData];
[parser setDelegate: self];
[parser setShouldResolveExternalEntities: YES];
[parser parse];
[connection release];
[webData release];
}
hey ankit you can get this code if at all its helpful to you no need to establish connection
just use this method
-(id)initWithURL:(NSURL*)url arrayRootObjectTags:(NSArray*)arrTags sel:(SEL)seletor andHandler:(NSObject*)handler{
if(self = [super init] ){
self.mainArray=arrTags;
self.MainHandler=handler;
self.targetSelector=seletor;
NSLog(#"%#",[url description]);
NSURLRequest *req=[NSURLRequest requestWithURL:url cachePolicy:NSURLCacheStorageNotAllowed timeoutInterval:30];
con=[[NSURLConnection alloc] initWithRequest:req delegate:self];
if(con){
myWebData=[[NSMutableData data] retain];
} else {
[MainHandler performSelector:#selector(targetSelector:) withObject:nil];
}
}
return self;
}
also the other supporting method
-(void)parser:(NSXMLParser*)parser didStartElement:(NSString*)elementName namespaceURI:(NSString*)namespaceURI qualifiedName:(NSString*)qualifiedName attributes:(NSDictionary*)attributeDict {
if([elementName isEqualToString:#"html"] || [elementName isEqualToString:#"HTML"]){
didGetHTML=YES; [self parserDidEndDocument:parser];
} else if([[mainArray objectAtIndex:0] isEqualToString:elementName] && [[mainArray objectAtIndex:1] isEqualToString:elementName] && !didGetHTML) {
objectsArray=[[NSMutableArray alloc] init];
tmpD=[[NSMutableDictionary alloc] init];
if(tmpOther==nil) tmpOther=[[NSMutableDictionary alloc] init];
} else if([[mainArray objectAtIndex:0] isEqualToString:elementName] && !didGetHTML ) {
objectsArray=[[NSMutableArray alloc] init];
if(tmpOther==nil) tmpOther=[[NSMutableDictionary alloc] init];
} else if([[mainArray objectAtIndex:1] isEqualToString:elementName] && !didGetHTML ) {
tmpD=[[NSMutableDictionary alloc] init];
} else if([mainArray containsObject:elementName] && !didGetHTML){
[tmpD setValue:[attributeDict valueForKey:#"data"] forKey:elementName];
}
}
-(void)parser:(NSXMLParser*)parser foundCharacters:(NSString*)string {
if(tmpString==nil && !didGetHTML){
tmpString=[[NSString alloc] initWithString:string];
} else if(!didGetHTML){
NSString *t=[NSString stringWithString:tmpString];
if([tmpString retainCount]>0) { [tmpString release]; tmpString=nil; }
tmpString=[[NSString alloc] initWithFormat:#"%#%#",t,string];
}
}
-(void)parser:(NSXMLParser*)parser didEndElement:(NSString*)elementName namespaceURI:(NSString*)namespaceURI qualifiedName:(NSString*)qualifiedName {
if([[mainArray objectAtIndex:0] isEqualToString:elementName] && [[mainArray objectAtIndex:1] isEqualToString:elementName] && !didGetHTML){
[objectsArray addObject:tmpD];
} else if([elementName isEqualToString:[mainArray objectAtIndex:1]] && !didGetHTML){
[objectsArray addObject:tmpD];
[tmpD release]; tmpD=nil;
} else if([mainArray containsObject:elementName] && !didGetHTML) {
if(![tmpD valueForKey:elementName]){
[tmpD setValue:tmpString forKey:elementName];
}
[tmpString release]; tmpString=nil;
} else {
[tmpOther setValue:tmpString forKey:elementName];
[tmpString release]; tmpString=nil;
}
}
and simply call the initwith url method from which ever class you have written this method
just you have to give root tag object tag and element tag of a particular object tag and also give selector after that take the response in dictionary and they take it in array and display the result according to your value for key