problem in copy string for other class - iphone

In my app I am sending a request to the web server and getting some results, then I am parsing this result and storing this result string into other class object string.
For example:
#interface GraphView : UIViewController<UITabBarControllerDelegate> {
NSMutableString *graphTempString;
}
#property(nonatomic,retain) NSMutableString *graphTempString;
#end
TSUClass .m
implementing NSURLConnection(),
connectionDidFinishLoading(),
-(void) parser:(NSXMLParser *) parser didStartElement:(NSString *) elementName
namespaceURI:(NSString *) namespaceURI qualifiedName:(NSString *) qName
attributes:(NSDictionary *) attributeDict()
-(void)parser:(NSXMLParser *)parser
didEndElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI
qualifiedName:(NSString *)qName
{
if( [elementName isEqualToString:#"statusTEResult"])
{
tempString=soapResults;
if (grpahCall == YES) {
graphViewController=[[GraphView alloc]init];
graphViewController.graphTempString=tempString;
[self.navigationController pushViewController:graphViewController animated:YES];
}
When I am debugging I can see the value of graphViewController.graphTempString but after going to GraphView, I am not able to see the values.
I hope some one know how to solve this issue.

Easy way to pass value.
[[NSUserDefaults standardUserDefaults]setObject:resultString forKey:#"resultString"];
[[NSUserDefaults standardUserDefaults] synchronize];
and in another class use this value like this
NSString *resultString=[[NSUserDefaults standardUserDefaults]valueForKey:#"resultString"];
or u may do it like this.
graphViewController.graphTempString=self.tempString;

can you try
2nClassObj.tempString =[NSString stringWithFormat:#"%#",resultString];
good luck

#Pooja i suggest you to try doing this by making a variable in AppDelegate class give your resultString to this variable and then fetch the value from this variable in your 2ndClass or in any class you want .....you will never get null value.
Lets suppose the object of your AppDelegate class is appDelegate and the variable which of NSString type is lets stringValue. Then in your class where you are getting the resultString do like this.
appDelegate.stringValue = resultString;
And in your 2ndClass class take the value from this variable like this.
tempString = appDelegate.stringValue;
You will get the data.....Hope you got my point.
Good Luck!

What happens if you add some NSLog statements?
if (grpahCall == YES) {
graphViewController=[[GraphView alloc]init];
NSLog(#"-%#-", tempString);
graphViewController.graphTempString=tempString;
NSLog(#"-%#-", graphViewcontroller.graphTempString);
[self.navigationController pushViewController:graphViewController animated:YES];
}
I would expect to see the same thing output twice? Can you tell me what you get in the console?

Related

How to parse 2 URL's using NSXMLParser in the same file?

how to parse 2 URL's using NSXMLParser in the same file? I have tried it like this:
[self parseXMLFileAtURL:url1];
[self parseXMLFileAtURL:url2];
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{
//here both url's returns the same data (element names are same), so how will I differentiate data between first URL & second URL.
if(url1 data) {
//do something
}
if(url2 data) {
//do something
}
}
so help me to find a way to differentiate.
I wouldn't. It's unnecessary. I would have 2 separate NSXMLParserDelegate handling each one. Or i would modify your current class to handle one file at a time, and have 2 instances of it.
You could create a separate delegate class within that class if that's what you like.
eg:
#implementation YourCurrentClass
#end
#interface ParserDelegate : NSObject <NSXMLParserDelegate>
#end
#implementation ParserDelegate
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI: (NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{
}
#end
Use multiple ParserDelegate instances to be the delegates of the parsing. Then have some other code that checks them for the result after they are finished processing.
I'm not sure but you can firstly add your URL objects to an array and later control by the elements of array instead of URL1 & URL2. You can try this:
NSString *obj;
NSMutableArray *urlArray;
[urlArray addObject:url1];
[urlArray addObject:url2];
in your parser method:
int i=[[urlArray objectAtIndex:obj] intValue];
switch(i){
case 0:
// we have url1 here
//do something with it
break;
case 1:
// we have url2 here
//do something...
break
}
i hope this point of view helps..
The first parameter called parser is the current parser instance used.
This is the way to know which file you are currently parsing.
Alloc/init two separate instances of NSXMLParser, and start parsing your two files with.
Assuming they are ivar a simple == test would tell you which one is used.
Here is a link to similar question.
Create 2 separate objects of NSXMLParser and assign tags and in delegate function check there tag and assign value according to tags.

How can I parse XML of having multiple Nodes with same name and show in different controller?

See the XML below
http://sosmoths.com/.xml/moths.xml
This XML having multiple images name, I have to show the different title(There are four title) in their respective Controller.
I have 4 controller, and have to show each moth value in different Controller, along with their multiple images values, how can I do it?
I can make single object of should I make four objects?
I am a bit confused in it, please help me.
This XML having multiple images name, I have to show the different
title(There are four title) in their respective Controller. I have 4
controller, and have to show each moth value in different Controller,
along with their multiple images values, how can I do it?
This sounds less like an XML parsing problem and more like an app architecture problem.
That XML basically describes some data and said data would typically be represented by objects in your application. You could go with a CoreData based solution whereby you parse the XML into a local CoreData store (in memory or on disk, matters not) and then display the managed objects as per usual.
Or, assuming that is representative of a typical set of data, you could parse it into your own hand rolled objects (or, even, dictionaries and arrays), then display from there.
There are dozens of questions about parsing XML on SO (and via Google).
The second part of your question hasn't been addressed. Basically, you need to properly layer your app into the model-view-controller pattern. Your model layer would parse the XML and create an object graph that represents the data. Each controller would have a reference to that single model.
This will work fine as long as your app is read only. If the various controllers are expected to also edit the object graph, then it'll need to be a bit more complex in that you'll have to deal with change propagation (this is where CoreData shines; it makes change management, propagation, validation, and undo relatively straightforward).
With TBXML you can easily parse the xml and it will convert it into objects to use:
http://www.tbxml.co.uk/TBXML/TBXML_Free.html
and libxml2 is also that you can use easily to parse.
try this it worked properly
-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict{
NSLog(#"%#",elementName);
if([elementName isEqualToString:#"moths"]){
mytblarray=[[NSMutableArray alloc] init];
} else if([elementName isEqualToString:#"moth"]){
tmpdic=[[NSMutableDictionary alloc] init];
}
else if([elementName isEqualToString:#"images"]){
imgArray=[[NSMutableArray alloc] init];
}
}
-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{
if(tmpstr!=nil && [tmpstr retainCount]>0){ [tmpstr release]; tmpstr=nil; }
tmpstr=[[NSString alloc] initWithString:string];
}
-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{
if([elementName isEqualToString:#"moth"]){
[mytblarray addObject:tmpdic];
[tmpdic release];
}if([elementName isEqualToString:#"images"]){
[tmpdic setValue:imgArray forKey:elementName];
}
else if([elementName isEqualToString:#"image"]){
[imgArray addObject:tmpstr];
}
else if([elementName isEqualToString:#"id"] || [elementName isEqualToString:#"title"]||[elementName isEqualToString:#"description"]){
[tmpdic setValue:tmpstr forKey:elementName];
}
}
-(void)parserDidEndDocument:(NSXMLParser *)parser{
NSLog(#"%#",[imgArray description]);
NSLog(#"%#",[mytblarray description]);
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
//get value like it
NSString *cellValue = [[mytblarray objectAtIndex:indexPath.row] valueForKey:#"id"];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
//get value like it
NSMutableDictionary *dict=[[NSMutableDictionary alloc]initWithDictionary:
[mytblarray objectAtIndex:indexPath.row]];
}

NSArray gives NSZombie error

I am trying to pass a single array object (that is a nsdictionary of several values) back to my main view.
basicly when I set the view up I parse some xml into an array of dictionaries. I then set up my tableview with one of the values inside the NSdictionary, this value is also used to set up the alphabetical scroller and section titles. (this is done in a method I created)
At the end of that method I call [self.tableView reloadData]; every thing loads up perfectly and everything displays fine.
Now what I am trying to do is set it up so that when a cell is selected, I check the value inside the cell.textlabel and use that as a predicate to check against my array of dictionaries once It finds the corresponding entry I want to pass that dictionary up to the main view with a delegate I have made.
however I am getting a error, that I think might be happening due to my reloadData.. but am not sure.
This is what my predicate looks like.
NSPredicate *pred = [NSPredicate predicateWithFormat:#"%K like %#",#"MANUFACTURER",cell.textLabel.text];
NSArray *filter = [myDataArray filteredArrayUsingPredicate:pred]; //error happens here
//check to see if the value is the correct one
NSLog(#"My Filtered array = %#", filter);
//once problem has been found set up the delegate here.
and this is the error message I receive.
2011-10-31 10:43:57.333 code[5812:207] *** -[__NSArrayM filteredArrayUsingPredicate:]: message sent to deallocated instance 0x6874210
myDataArray is created in the NSXMLParser delegates as listed below.
//.h
NSMutableArray *myDataArray;
}
#property (nonatomic, retain) NSMutableArray *myDataArray;
//.m
#pragma mark - Parsing lifecycle
- (void)startTheParsingProcess:(NSData *)parserData
{
//myDataArray = [NSMutableArray arrayWithCapacity:8]; // not even sure if this is needed as its declared later on.
NSXMLParser *parser = [[NSXMLParser alloc] initWithData:parserData]; //parserData passed to NSXMLParser delegate which starts the parsing process
[parser setDelegate:self];
[parser parse]; // starts the event-driven parsing operation.
[parser release];
}
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
if([elementName isEqualToString:#"Row"])
{
manufactureMutableDictionary = [[NSMutableDictionary alloc] initWithDictionary:attributeDict];
}
if([elementName isEqualToString:#"Rows"])
{
myDataArray = [NSMutableArray arrayWithCapacity:8];
}
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
if([elementName isEqualToString:#"Row"])
{
[myDataArray addObject:manufactureMutableDictionary];
}
[manufactureMutableDictionary release];
manufactureMutableDictionary = nil;
}
Any help would be greatly appreciated, also do you think I am going about passing all the values of the dictionary the right way?
You are using an autoreleased array
myDataArray = [NSMutableArray arrayWithCapacity:8];
You have properties set up so use them e.g.
self.myDataArray = [NSMutableArray arrayWithCapacity:8];
or even better
NSMutableArray *tmpMyDataArray = [[NSMutableArray alloc] initWithCapacity:8];
self.myDataArray = tmpMyDataArray;
[tmpMyDataArray release]; tmpMyDataArray = nil;

Parse Nested XML Objective C - NSXMLParser

All,
I have XML in the following format:
<linked-list>
<Description>
<desc></desc>
<IP></IP>
</Description>
</linked-list>
This XML statement could have an infinite number of <Description></Description> inside of the <linked-list></linked-list>.
How should I parse this using NSXMLParser? My current code is as follows, but it parses incorrectly.
#implementation XMLParser
#synthesize response;
- (XMLParser *) initXMLParser
{
self = [super init];
// init dictionary of response data
response = [[NSMutableDictionary alloc] init];
return self;
}
//Gets Start Element of SessionData
- (void)parser:(NSXMLParser *)parser
didStartElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI
qualifiedName:(NSString *)qualifiedName
attributes:(NSDictionary *)attributeDict
{
if ([elementName isEqualToString:#"linked-list"])
{
NSLog(#"Found linked-list in the return XML! Continuing...");
//response is a NSMutableArray instance variable
//THIS SHOULD NEVER NEED TO BE USED
if (!response)//if array is empty, it makes it!
{
NSLog(#"Dictionary is empty for some reason, creating...");
response = [[NSMutableDictionary alloc] init];
}
//END: THIS SHOULD NEVER BE USED
return;
}
else
{
currentElementName = elementName;
NSLog(#"Current Element Name = %#", currentElementName);
return;
}
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
if (!currentElementValue) {
// init the ad hoc string with the value
currentElementValue = [[NSMutableString alloc] initWithString:string];
} else {
[currentElementValue setString:string];
NSLog(#"Processing value for : %#", string);
}
}
//Gets End Element of linked-list
- (void)parser:(NSXMLParser *)parser
didEndElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI
qualifiedName:(NSString *)qName {
if ([elementName isEqualToString:#"linked-list"])
{
// We reached the end of the XML document
// dumps dictionary into log
NSLog(#"Dump:%#", [response description]);
return;
}
else
{
//Adds key and object to dictionary
[response setObject:currentElementValue forKey:currentElementName];
NSLog(#"Set values, going around again... brb.");
}
currentElementValue = nil;
currentElementName = nil;
}
#end
Some observations:
An infinite number of WHAT inside of the WHAT?
Assuming there can be more than one Description element, the outer data structure in which you store the contents must be a NSMutableArray, not a dictionary. You then use one mutable dictionary per Description element.
Consequently, in didStartElement:, check if the element name is #"Description" and if so, create a new NSMutableDictionary instance that you store in an ivar.
In foundCharacters:, you always have to append the new characters to the existing currentElementValue because the method can be called multiple times for each element's contents. I see many people do this wrong despite the fact that Apple's sample code clearly demonstrates the correct way.
In didEndElement:, do this:
If the element name is #"desc" or #"IP", assign currentElementValue to the corresponding key in your current mutable dictionary. Don't forget to release currentElementValue before you set it to nil. You currently have a memory leak in your code because you're not doing that.
If the element name is #"Description", add the current mutable dictionary to the mutable array. Release the dictionary and set the ivar to nil. A new dictionary will be created the next time you encounter a #"Description" element in didStartElement:.
If the element name is #"linked-list", the mutable array will contain all the dictionaries and you're done.

Memory Leak with NSXMLParser on IPhone

below is my code, Leaks says I am getting a memory leak around NSMutableString alloc method. I am sure it is something I simply overlooked, let me know if anyone has any thoughts. Thanks!
-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{
if (!currentValue) {
currentValue = [[NSMutableString alloc] initWithCapacity:[string length]];
}
[currentValue setString:[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]];
}
-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{
if([elementName isEqualToString:#"phone"]){
currentAgent.phone = currentValue;
}
[currentValue release];
currentValue = nil;
}
-Agent is a custom object that was created when the class was initialized. The XML is valid and has all the appropriate begin/end tags.
Looking over this code, I think it's more likely that your Agent class is leaking phone. Assuming Agent uses retain for the phone property, this will cause the phone to persist longer than it should.
The creator of the object gets "credited" with the leak, even if the extra retain is somewhere else.
In other words, in Agent:
- (void)dealloc {
self.phone = nil;
// anything else you need to do
[super dealloc];
}