Search Results

Search found 126 results on 6 pages for 'nsxmlparser'.

Page 5/6 | < Previous Page | 1 2 3 4 5 6  | Next Page >

  • NSConcreteData leaked object in objective c ?

    - by Madan Mohan
    Hi Guys, I am getting the NSConcreteData leaked object while testing the leaks in the instruments.It showing in the parser, - (void)parseXMLFileAtURL:(NSURL *)URL { [urlList release]; urlList = [[NSMutableArray alloc] init]; myParser = [[NSXMLParser alloc] initWithContentsOfURL:URL] ;// it showing this line as leaking [myParser setDelegate:self]; [myParser setShouldProcessNamespaces:NO]; [myParser setShouldReportNamespacePrefixes:NO]; [myParser setShouldResolveExternalEntities:NO]; [myParser parse]; [myParser release]; }

    Read the article

  • Adding Custom Object to NSMutableArray

    - by Fozz
    Developing ios app. I have an object class Product.h and .m respectively along with my picker class which implements my vehicle selection to match products to vehicle. The files product.h #import <Foundation/Foundation.h> @interface Product : NSObject { } @property (nonatomic, retain) NSString *iProductID; @property (nonatomic, retain) NSString *vchProductCode; @property (nonatomic, retain) NSString *vchPriceCode; @property (nonatomic, retain) NSString *vchHitchUPC; @property (nonatomic, retain) NSString *mHitchList; @property (nonatomic, retain) NSString *mHitchMap; @property (nonatomic, retain) NSString *fShippingWeight; @property (nonatomic, retain) NSString *vchWC; @property (nonatomic, retain) NSString *vchCapacity; @property (nonatomic, retain) NSString *txtNote1; @property (nonatomic, retain) NSString *txtNote2; @property (nonatomic, retain) NSString *txtNote3; @property (nonatomic, retain) NSString *txtNote4; @property (nonatomic, retain) NSString *vchDrilling; @property (nonatomic, retain) NSString *vchUPCList; @property (nonatomic, retain) NSString *vchExposed; @property (nonatomic, retain) NSString *vchShortDesc; @property (nonatomic, retain) NSString *iVehicleID; @property (nonatomic, retain) NSString *iProductClassID; @property (nonatomic, retain) NSString *dtDateMod; @property (nonatomic, retain) NSString *txtBullet1; @property (nonatomic, retain) NSString *txtBullet2; @property (nonatomic, retain) NSString *txtBullet3; @property (nonatomic, retain) NSString *txtBullet4; @property (nonatomic, retain) NSString *txtBullet5; @property (nonatomic, retain) NSString *iUniqueIdentifier; @property (nonatomic, retain) NSString *dtDateLastTouched; @property (nonatomic, retain) NSString *txtNote6; @property (nonatomic, retain) NSString *InstallTime; @property (nonatomic, retain) NSString *SGID; @property (nonatomic, retain) NSString *CURTID; @property (nonatomic, retain) NSString *SGRetail; @property (nonatomic, retain) NSString *SGMemPrice; @property (nonatomic, retain) NSString *InstallSheet; @property (nonatomic, retain) NSString *mHitchJobber; @property (nonatomic, retain) NSString *CatID; @property (nonatomic, retain) NSString *ParentID; -(id) initWithDict:(NSDictionary *)dic; -(NSString *) description; @end Product implementation .m #import "Product.h" @implementation Product @synthesize iProductID; @synthesize vchProductCode; @synthesize vchPriceCode; @synthesize vchHitchUPC; @synthesize mHitchList; @synthesize mHitchMap; @synthesize fShippingWeight; @synthesize vchWC; @synthesize vchCapacity; @synthesize txtNote1; @synthesize txtNote2; @synthesize txtNote3; @synthesize txtNote4; @synthesize vchDrilling; @synthesize vchUPCList; @synthesize vchExposed; @synthesize vchShortDesc; @synthesize iVehicleID; @synthesize iProductClassID; @synthesize dtDateMod; @synthesize txtBullet1; @synthesize txtBullet2; @synthesize txtBullet3; @synthesize txtBullet4; @synthesize txtBullet5; @synthesize iUniqueIdentifier; @synthesize dtDateLastTouched; @synthesize txtNote6; @synthesize InstallTime; @synthesize SGID; @synthesize CURTID; @synthesize SGRetail; @synthesize SGMemPrice; @synthesize InstallSheet; @synthesize mHitchJobber; @synthesize CatID; @synthesize ParentID; -(id) initWithDict:(NSDictionary *)dic { [super init]; //Initialize all variables self.iProductID = [[NSString alloc] initWithString:[dic objectForKey:@"iProductID"]]; self.vchProductCode = [[NSString alloc] initWithString:[dic objectForKey:@"vchProductCode"]]; self.vchPriceCode = [[NSString alloc] initWithString:[dic objectForKey:@"vchPriceCode"]]; self.vchHitchUPC = [[NSString alloc] initWithString:[dic objectForKey:@"vchHitchUPC"]]; self.mHitchList = [[NSString alloc] initWithString:[dic objectForKey:@"mHitchList"]]; self.mHitchMap = [[NSString alloc] initWithString:[dic objectForKey:@"mHitchMap"]]; self.fShippingWeight = [[NSString alloc] initWithString:[dic objectForKey:@"fShippingWeight"]]; self.vchWC = [[NSString alloc] initWithString:[dic objectForKey:@"vchWC"]]; self.vchCapacity = [[NSString alloc] initWithString:[dic objectForKey:@"vchCapacity"]]; self.txtNote1 = [[NSString alloc] initWithString:[dic objectForKey:@"txtNote1"]]; self.txtNote2 = [[NSString alloc] initWithString:[dic objectForKey:@"txtNote2"]]; self.txtNote3 = [[NSString alloc] initWithString:[dic objectForKey:@"txtNote3"]]; self.txtNote4 = [[NSString alloc] initWithString:[dic objectForKey:@"txtNote4"]]; self.vchDrilling = [[NSString alloc] initWithString:[dic objectForKey:@"vchDrilling"]]; self.vchUPCList = [[NSString alloc] initWithString:[dic objectForKey:@"vchUPCList"]]; self.vchExposed = [[NSString alloc] initWithString:[dic objectForKey:@"vchExposed"]]; self.vchShortDesc = [[NSString alloc] initWithString:[dic objectForKey:@"vchShortDesc"]]; self.iVehicleID = [[NSString alloc] initWithString:[dic objectForKey:@"iVehicleID"]]; self.iProductClassID = [[NSString alloc] initWithString:[dic objectForKey:@"iProductClassID"]]; self.dtDateMod = [[NSString alloc] initWithString:[dic objectForKey:@"dtDateMod"]]; self.txtBullet1 = [[NSString alloc] initWithString:[dic objectForKey:@"txtBullet1"]]; self.txtBullet2 = [[NSString alloc] initWithString:[dic objectForKey:@"txtBullet2"]]; self.txtBullet3 = [[NSString alloc] initWithString:[dic objectForKey:@"txtBullet3"]]; self.txtBullet4 = [[NSString alloc] initWithString:[dic objectForKey:@"txtBullet4"]]; self.txtBullet5 = [[NSString alloc] initWithString:[dic objectForKey:@"txtBullet5"]]; self.iUniqueIdentifier = [[NSString alloc] initWithString:[dic objectForKey:@"iUniqueIdentifier"]]; self.dtDateLastTouched = [[NSString alloc] initWithString:[dic objectForKey:@"dtDateLastTouched"]]; self.txtNote6 = [[NSString alloc] initWithString:[dic objectForKey:@"txtNote6"]]; self.InstallTime = [[NSString alloc] initWithString:[dic objectForKey:@"InstallTime"]]; self.SGID = [[NSString alloc] initWithString:[dic objectForKey:@"SGID"]]; self.CURTID = [[NSString alloc] initWithString:[dic objectForKey:@"CURTID"]]; self.SGRetail = [[NSString alloc] initWithString:[dic objectForKey:@"SGRetail"]]; self.SGMemPrice = [[NSString alloc] initWithString:[dic objectForKey:@"SGMemPrice"]]; self.InstallSheet = [[NSString alloc] initWithString:[dic objectForKey:@"InstallSheet"]]; self.mHitchJobber = [[NSString alloc] initWithString:[dic objectForKey:@"mHitchJobber"]]; self.CatID = [[NSString alloc] initWithString:[dic objectForKey:@"CatID"]]; self.ParentID = [[NSString alloc] initWithString:[dic objectForKey:@"ParentID"]]; return self; } -(NSString *) description { return [NSString stringWithFormat:@"iProductID = %@\n vchProductCode = %@\n vchPriceCode = %@\n vchHitchUPC = %@\n mHitchList = %@\n mHitchMap = %@\n fShippingWeight = %@\n vchWC = %@\n vchCapacity = %@\n txtNote1 = %@\n txtNote2 = %@\n txtNote3 = %@\n txtNote4 = %@\n vchDrilling = %@\n vchUPCList = %@\n vchExposed = %@\n vchShortDesc = %@\n iVehicleID = %@\n iProductClassID = %@\n dtDateMod = %@\n txtBullet1 = %@\n txtBullet2 = %@\n txtBullet3 = %@\n txtBullet4 = %@\n txtBullet4 = %@\n txtBullet5 = %@\n iUniqueIdentifier = %@\n dtDateLastTouched = %@\n txtNote6 = %@\n InstallTime = %@\n SGID = %@\n CURTID = %@\n SGRetail = %@\n SGMemPrice = %@\n InstallSheet = %@\n mHitchJobber = %@\n CatID = %@\n ParentID = %@\n", iProductID, vchProductCode, vchPriceCode, vchHitchUPC, mHitchList, mHitchMap, fShippingWeight, vchWC, vchCapacity, txtNote1, txtNote2, txtNote3, txtNote4, vchDrilling, vchUPCList, vchExposed, vchShortDesc, iVehicleID, iProductClassID, dtDateMod, txtBullet1, txtBullet2, txtBullet3, txtBullet4,txtBullet5, iUniqueIdentifier, dtDateLastTouched,txtNote6,InstallTime,SGID,CURTID,SGRetail,SGMemPrice,InstallSheet,mHitchJobber,CatID, ParentID]; } @end Ignoring the fact that its really long I also tried to just set the property but then my product didnt have any values. So I alloc'd for all properties, not sure which is "correct" the use of product picker.h #import <UIKit/UIKit.h> @class Vehicle; @class Product; @interface Picker : UITableViewController <NSXMLParserDelegate> { NSString *currentRow; NSString *currentElement; Vehicle *vehicle; } @property (nonatomic, retain) NSMutableArray *dataArray; //@property (readwrite, copy) NSString *currentRow; //@property (readwrite, copy) NSString *currentElement; -(void) getYears:(NSString *)string; -(void) getMakes:(NSString *)year; -(void) getModels:(NSString *)year: (NSString *)make; -(void) getStyles:(NSString *)year: (NSString *)make: (NSString *)model; -(void) getHitch:(NSString *)year: (NSString *)make: (NSString *)model: (NSString *)style; -(void) parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName; -(void) parser:(NSXMLParser *)parser foundCharacters:(NSString *)string; -(void) parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict; @end The implementation .m #import "Product.h" #import "Picker.h" #import "KioskAppDelegate.h" #import "JSON.h" #import "Vehicle.h" @implementation Picker @synthesize dataArray; -(void) getHitch:(NSString *)year: (NSString *)make: (NSString *)model: (NSString *)style{ currentRow = [NSString stringWithString:@"z:row"]; currentElement = [NSString stringWithString:@"gethitch"]; //Reinitialize data array [self.dataArray removeAllObjects]; [self.dataArray release]; self.dataArray = [[NSArray alloc] initWithObjects:nil]; //Build url & string NSString *thisString = [[NSString alloc] initWithString:@""]; thisString = [NSString stringWithFormat:@"http://api.curthitch.biz/AJAX_CURT.aspx?action=GetHitch&dataType=json&year=%@&make=%@&model=%@&style=%@",year,make,model,style]; //Request NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:thisString]]; //Perform request and fill data with json NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil]; //Get string from data NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding]; //set up parser SBJsonParser *parser = [[SBJsonParser alloc] init]; //parse json into object NSArray *tempArray = [parser objectWithString:json_string error:nil]; for (NSDictionary *dic in tempArray) { Product *tempProduct = [[Product alloc] initWithDict:dic]; NSLog(@"is tempProduct valid %@", (tempProduct) ? @"YES" : @"NO"); [self.dataArray addObject:tempProduct]; } } @end So I stripped out all the table methods and misc crap that doesnt matter. In the end my problem is adding the "tempProduct" object to the mutable array dataArray so that I can customize the table cells. Using the json framework im parsing out some json which returns an array of NSDictionary objects. Stepping through that my dictionary objects look good, I populate my custom object with properties for all my fields which goes through fine, and the values look right. However I cant add this to the array, I've tried several different implementations doesn't work. Not sure what I'm doing wrong. In some instances doing a po tempProduct prints the description and sometimes it does not. same with right clicking on the variable and choosing print description. Actual error message 2011-02-22 15:53:56.058 Kiosk[8547:207] -[__NSArrayI addObject:]: unrecognized selector sent to instance 0x4e1ba40 2011-02-22 15:53:56.060 Kiosk[8547:207] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSArrayI addObject:]: unrecognized selector sent to instance 0x4e1ba40' *** Call stack at first throw: ( 0 CoreFoundation 0x00dbabe9 __exceptionPreprocess + 185 1 libobjc.A.dylib 0x00f0f5c2 objc_exception_throw + 47 2 CoreFoundation 0x00dbc6fb -[NSObject(NSObject) doesNotRecognizeSelector:] + 187 3 CoreFoundation 0x00d2c366 ___forwarding___ + 966 4 CoreFoundation 0x00d2bf22 _CF_forwarding_prep_0 + 50 5 Kiosk 0x00003ead -[Picker getHitch::::] + 1091 6 Kiosk 0x00003007 -[Picker tableView:didSelectRowAtIndexPath:] + 1407 7 UIKit 0x0009b794 -[UITableView _selectRowAtIndexPath:animated:scrollPosition:notifyDelegate:] + 1140 8 UIKit 0x00091d50 -[UITableView _userSelectRowAtPendingSelectionIndexPath:] + 219 9 Foundation 0x007937f6 __NSFireDelayedPerform + 441 10 CoreFoundation 0x00d9bfe3 __CFRUNLOOP_IS_CALLING_OUT_TO_A_TIMER_CALLBACK_FUNCTION__ + 19 11 CoreFoundation 0x00d9d594 __CFRunLoopDoTimer + 1220 12 CoreFoundation 0x00cf9cc9 __CFRunLoopRun + 1817 13 CoreFoundation 0x00cf9240 CFRunLoopRunSpecific + 208 14 CoreFoundation 0x00cf9161 CFRunLoopRunInMode + 97 15 GraphicsServices 0x0102e268 GSEventRunModal + 217 16 GraphicsServices 0x0102e32d GSEventRun + 115 17 UIKit 0x0003442e UIApplicationMain + 1160 18 Kiosk 0x0000239a main + 104 19 Kiosk 0x00002329 start + 53 ) terminate called after throwing an instance of 'NSException'

    Read the article

  • Application crashing on getting updated information from database using timer and storing it on loca

    - by Amit Battan
    In our multi - user application we are continuously interacting with database. We have a common class through which we are sending POST queries to database and obtaining xml files in return. We are using delegates of NSXMLParser to parse the obtained file. The problem with us is we are facing many crashes in it generally when application is idle and changed data in database is being fetched in background through timer which is invoked after every few seconds. We have also dealt with error handling through try and catch but it proves to be of no use in this case and mostly application crashes with following error : Exception Type: EXC_BAD_ACCESS (SIGBUS) Exception Codes: KERN_PROTECTION_FAILURE at 0x0000000000000020 Strange thing is that many times the fetching of updated data at background works very fine, same methods being successfully executed under similar conditions but suddenly it crashes on one of them. The codes we are using is as follows: // we are using timer in this way: chkOnlineUser=[NSTimer scheduledTimerWithTimeInterval:15 target:mmObject selector:@selector(threadOnlineUser) userInfo:NULL repeats:YES]; // this method being called in timer -(void)threadOnlineUser{//HeartBeat in Thread [NSThread detachNewThreadSelector:@selector(onlineUserRefresh) toTarget:self withObject:nil]; } // this performs actual updation -(void)onlineUserRefresh{ NSAutoreleasePool *pool =[[NSAutoreleasePool alloc]init]; @try{ if(chkTimer==1){ return; } chkTimer=1; if([allUserArray count]==0){ [user parseXMLFileUser:@"all" andFlag:3]; [allUserArray removeAllObjects]; [allUserArray addObjectsFromArray:[user users]]; } [objHeartBeat parseXMLFile:[loginID intValue] timeOut:10]; NSMutableDictionary *tDictOL=[[NSMutableDictionary alloc] init]; tDictOL=[objHeartBeat onLineList]; NSArray *tArray=[[NSArray alloc] init]; tArray=[[tDictOL objectForKey:@"onlineuser"] componentsSeparatedByString:@","]; [loginUserArray removeAllObjects]; for(int l=0;l less than [tArray count] ;l++){ int t;//=[[tArray objectAtIndex:l] intValue]; if([[allUserArray valueForKey:@"Id"] containsObject:[tArray objectAtIndex:l]]){ t = [[allUserArray valueForKey:@"Id"] indexOfObject:[tArray objectAtIndex:l]]; [loginUserArray addObject:[allUserArray objectAtIndex:t]]; } } [onlineTable reloadData]; [logInUserPopUp removeAllItems]; if([loginUserArray count]==1){ [labelLoginUser setStringValue:@"Only you are online"]; [logInUserPopUp setEnabled:YES]; }else{ [labelLoginUser setStringValue:[NSString stringWithFormat:@" %d users online",[loginUserArray count]]]; [logInUserPopUp setEnabled:YES]; } NSMenu *menu = [[NSMenu alloc] initWithTitle:@"menu"]; NSMenuItem *itemOne = [[NSMenuItem alloc] initWithTitle:@"" action:NULL keyEquivalent:@""]; [menu addItem:itemOne]; for(int l=0;l less than [loginUserArray count];l++){ NSString *tempStr= [NSString stringWithFormat:@"%@ %@",[[[loginUserArray objectAtIndex:l] objectForKey:@"user_fname"] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]],[[[loginUserArray objectAtIndex:l] objectForKey:@"user_lname"] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]]; if(![tempStr isEqualToString:@""]){ NSMenuItem *itemOne = [[NSMenuItem alloc] initWithTitle:tempStr action:NULL keyEquivalent:@""]; [menu addItem:itemOne]; }else if(l==0){ NSMenuItem *itemOne = [[NSMenuItem alloc] initWithTitle:tempStr action:NULL keyEquivalent:@""]; [menu addItem:itemOne]; } } [logInUserPopUp setMenu:menu]; if([lastUpdateTime isEqualToString:@""]){ }else { [self fetchUpdatedInfo:lastUpdateTime]; [self fetchUpdatedGroup:lastUpdateTime];// function same as fetchUpdatedInfo [avObject fetchUpdatedInfo:lastUpdateTime];// function same as fetchUpdatedInfo [esTVObject fetchUpdatedInfo:lastUpdateTime];// function same as fetchUpdatedInfo } lastUpdateTime=[[tDictOL objectForKey:@"lastServerTime"] copy]; } @catch (NSException * e) { [queryByPost insertException:@"MainModule" inFun:@"onlineUserRefresh" excp:[e description] userId:[loginID intValue]]; NSRunAlertPanel(@"Error Panel", @"Main Module- onlineUserRefresh....%@", @"OK", nil, nil,e); } @finally { NSLog(@"Internal Update Before Bye"); chkTimer=0; NSLog(@"Internal Update Bye");// Some time application crashes after this log // Some time application crahses after "Internal Update Bye" log } } // The method which we are using to obtain updated data is of following form: -(void)fetchUpdatedInfo:(NSString *)UpdTime{ @try { if(initAfterLoginComplete==0){ return; } [user parseXMLFileUser:UpdTime andFlag:[loginID intValue]]; [tempUserUpdatedArray removeAllObjects]; [tempUserUpdatedArray addObjectsFromArray:[user users]]; if([tempUserUpdatedArray count]0){ if([contactsView isHidden]){ [topContactImg setImage:[NSImage imageNamed:@"btn_contacts_off_red.png"]]; }else { [topContactImg setImage:[NSImage imageNamed:@"btn_contacts_red.png"]]; } }else { return; } int chkprof=0; for(int l=0;l less than [tempUserUpdatedArray count];l++){ NSArray *tempArr1 = [allUserArray valueForKey:@"Id"]; int s; if([[[tempUserUpdatedArray objectAtIndex:l] objectForKey:@"Id"] intValue]==profile_Id){ chkprof=1; } if([tempArr1 containsObject:[[tempUserUpdatedArray objectAtIndex:l] objectForKey:@"Id"]]){ s = [tempArr1 indexOfObject:[[tempUserUpdatedArray objectAtIndex:l] objectForKey:@"Id"]]; [allUserArray replaceObjectAtIndex:s withObject:[tempUserUpdatedArray objectAtIndex:l]]; }else { [allUserArray addObject:[tempUserUpdatedArray objectAtIndex:l]]; } NSArray *tempArr2 = [tempUser valueForKey:@"Id"]; if([tempArr2 containsObject:[[tempUserUpdatedArray objectAtIndex:l] objectForKey:@"Id"]]){ s = [tempArr2 indexOfObject:[[tempUserUpdatedArray objectAtIndex:l] objectForKey:@"Id"]]; [tempUser replaceObjectAtIndex:s withObject:[tempUserUpdatedArray objectAtIndex:l]]; }else { [tempUser addObject:[tempUserUpdatedArray objectAtIndex:l]]; } } NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"user_fname" ascending:YES]; [tempUser sortUsingDescriptors:[NSMutableArray arrayWithObject:sortDescriptor]]; [userListTableView reloadData]; [groupsArray removeAllObjects]; for(int z=0;z less than [tempGroups count];z++){ NSMutableArray *tempMArr=[[NSMutableArray alloc] init]; for(int l=0;l less than [allUserArray count];l++){ if([[[allUserArray objectAtIndex:l] objectForKey:@"GroupId"] intValue]==[[[tempGroups objectAtIndex:z] objectForKey:@"group_id"] intValue]){ [tempMArr addObject:[allUserArray objectAtIndex:l]]; } } [groupsArray insertObject:tempMArr atIndex:z]; [tempMArr release]; tempMArr= nil; } for(int n=0;n less than [tempGroups count];n++){ [[groupsArray objectAtIndex:n] addObject:[tempGroups objectAtIndex:n]]; } [groupsListOV reloadData]; if(chkprof==1){ [self profileShow:profile_Id]; }else { } [self selectUserInTable:0]; }@catch (NSException * e) { NSRunAlertPanel(@"Error Panel", @"%@", @"OK", nil, nil,e); } } // The method which we are using to frame select query and parse obtained data is: -(void)parseXMLForUser:(int)UId stringVar:(NSString*)stringVar{ @try{ if(queryByPost) [queryByPost release]; queryByPost=[QueryByPost new]; // common class used to invoke method to send request via POST method //obtaining data for xml parsing NSString *query=[NSString stringWithFormat:@"Select * from userinfo update_time = '%@' AND NOT owner_id ='%d' ",stringVar,UId]; NSData *obtainedData=[queryByPost executeQuery:query WithAction:@"query"]; // method invoked to perform post query if(obtainedData==nil){ // data not obtained so return return; } // initializing dictionary to be obtained after parsing if(obtainedDictionary) [obtainedDictionary release]; obtainedDictionary=[NSMutableDictionary new]; // xml parsing if (updatedDataParser) // airportsListParser is an NSXMLParser instance variable [updatedDataParser release]; updatedDataParser = [[NSXMLParser alloc] initWithData:obtainedData]; [updatedDataParser setDelegate:self]; [updatedDataParser setShouldResolveExternalEntities:YES]; BOOL success = [updatedDataParser parse]; } @catch (NSException *e) { NSLog(@"wtihin parseXMLForUser- parseXMLForUser:stringVar: - %@",[e description]); } } //The method which will attempt to interact 4 times with server if interaction with it is found to be unsuccessful , is of following form: -(NSData*)executeQuery:(NSString*)query WithAction:(NSString*)doAction{ NSLog(@"within ExecuteQuery:WithAction: Query is: %@ and Action is: %@",query,doAction); NSString *returnResult; @try { NSString *returnResult; NSMutableURLRequest *postRequest; NSError *error; NSData *searchData; NSHTTPURLResponse *response; postRequest=[self directMySQLQuery:query WithAction:doAction]; // this method sends actual POST request NSLog(@"after directMYSQL in QueryByPost- performQuery... ErrorLogMsg"); searchData = [NSURLConnection sendSynchronousRequest:postRequest returningResponse:&response error:&error]; returnResult = [[NSString alloc] initWithData:searchData encoding:NSASCIIStringEncoding]; NSString *resultToBeCompared=[returnResult stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; NSLog(@"result obtained - %@/ resultToBeCompared - %@",returnResult,resultToBeCompared); if(![resultToBeCompared isEqualToString:@""]){ }else { sleep(10); postRequest=[self directMySQLQuery:query WithAction:doAction]; searchData = [NSURLConnection sendSynchronousRequest:postRequest returningResponse:&response error:&error]; if(![resultToBeCompared isEqualToString:@""]){ }else { sleep(10); postRequest=[self directMySQLQuery:query WithAction:doAction]; searchData = [NSURLConnection sendSynchronousRequest:postRequest returningResponse:&response error:&error]; if(![resultToBeCompared isEqualToString:@""]){ }else { sleep(10); postRequest=[self directMySQLQuery:query WithAction:doAction]; searchData = [NSURLConnection sendSynchronousRequest:postRequest returningResponse:&response error:&error]; if(![resultToBeCompared isEqualToString:@""]){ }else { sleep(10); postRequest=[self directMySQLQuery:query WithAction:doAction]; searchData = [NSURLConnection sendSynchronousRequest:postRequest returningResponse:&response error:&error]; if(![resultToBeCompared isEqualToString:@""]){ }else { return nil; } } } } } returnResult = [[NSString alloc] initWithData:searchData encoding:NSASCIIStringEncoding]; return searchData; } @catch (NSException * e) { NSLog(@"within QueryByPost , execurteQuery:WithAction - %@",[e description]); return nil; } } // The method which sends POST request to server , is of following form: -(NSMutableURLRequest *)directMySQLQuery:(NSString*)query WithAction:(NSString*)doAction{ @try{ NSLog(@"Query is: %@ and Action is: %@",query,doAction); // some pre initialization NSString *stringBoundary,*contentType; NSURL *cgiUrl ; NSMutableURLRequest *postRequest; NSMutableData *postBody; NSString *ans=@"434"; cgiUrl = [NSURL URLWithString:@"http://keysoftwareservices.com/API.php"]; postRequest = [NSMutableURLRequest requestWithURL:cgiUrl]; [postRequest setHTTPMethod:@"POST"]; stringBoundary = [NSString stringWithString:@"0000ABCQueryxxxxxx"]; contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", stringBoundary]; [postRequest addValue:contentType forHTTPHeaderField: @"Content-Type"]; //setting up the body: postBody = [NSMutableData data]; [postBody appendData:[[NSString stringWithFormat:@"\r\n\r\n--%@\r\n",stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]]; [postBody appendData:[[NSString stringWithString:@"Content-Disposition: form-data; name=\"code\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]]; [postBody appendData:[[NSString stringWithString:ans] dataUsingEncoding:NSUTF8StringEncoding]]; [postBody appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]]; [postBody appendData:[[NSString stringWithString:@"Content-Disposition: form-data; name=\"action\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]]; [postBody appendData:[[NSString stringWithString:doAction] dataUsingEncoding:NSUTF8StringEncoding]]; [postBody appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]]; [postBody appendData:[[NSString stringWithString:@"Content-Disposition: form-data; name=\"devmode\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]]; [postBody appendData:[[NSString stringWithString:[[[NSBundle mainBundle] infoDictionary] objectForKey:@"devmode"]] dataUsingEncoding:NSUTF8StringEncoding]]; [postBody appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]]; [postBody appendData:[[NSString stringWithString:@"Content-Disposition: form-data; name=\"q\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]]; [postBody appendData:[[NSString stringWithString:query] dataUsingEncoding:NSUTF8StringEncoding]]; [postBody appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]]; [postRequest setHTTPBody:postBody]; NSLog(@"Direct My SQL ok");// Some time application crashes afte this log //Some time application crashes after "Direct My SQL ok" log return [postRequest mutableCopy]; }@catch (NSException * e) { NSLog(@"NSException %@",e); NSRunAlertPanel(@"Error Panel", @"Within QueryByPost- directMySQLQuery...%@", @"OK", nil, nil,e); return nil; } }

    Read the article

  • Accessing Instance Attributes from Secondary Thread (iPhone-SDK)

    - by Travis
    I have a class with an NSDictionary attribute. Inside this class I dispatch another thread to handle NSXMLParser handling. Inside my -didStartElement, I access the dictionary in the class (to compare an element found in the XML to one in the dictionary). At this point I get undefined results. Using NSLog (I'm not advanced in XCode debugging), I see that it bombs around access of the NSDictionary. I tried just iterating the dictionary and dumping the key/values inside the didStartElement and this bombs at different keys each time. The only thing I can conclude is that something is not kosher that I'm doing with regards to accessing main thread attributes from the secondary thread. I'm somewhat new to multithreading and am not sure what the best protocol is safely access attributes from additional threads. Thanks all.

    Read the article

  • Collection <NSCFSet: 0x1b0b30> was mutated while being enumerated. How to determine which set?

    - by jamone
    I'm doing a bunch of core data inserts and after 20k or so inserts with saves every 1-2k I get this error: Terminating app due to uncaught exception 'NSGenericException', reason: '*** Collection <NSCFSet: 0x1b0b30> was mutated while being enumerated.' I'm trying to figure out which NSSet is causing this. I've done a search and the only NSSets in my code are the autogenerated ones that handle the Core Data relationships. I'm using NSXMLParser and for each element found creating a new entity (if a matching one doesn't already exist). So I will create a state entity and then populate all the city entities and then do a save. This means that a state's NSSet *cities is getting added to but I don't see why you can't do that.

    Read the article

  • Accessing XML data online?

    - by fuzzygoat
    I am just testing an app to get data off our web server, previously I had been using: NSURL, NSURLRequest, NSURLConnection etc. to get the data that I wanted. But I have just noticed that if I swap to using XML I can simply do the following and pass the results to NSXMLParser: NSURL *url = [NSURL URLWithString:@"https://www.fuzzygoat.com/turbine?nbytes=1&fmt=xml"]; Am I right in thinking that if your just after XML this is an acceptable method? It just seems strongly short compared to what I was doing before? gary

    Read the article

  • iPhone, Convenience Method or Alloc / Release?

    - by fuzzygoat
    Whilst developing for the iPhone I had a stubborn memory leak that I eventually tracked down to NSXMLParser. However whilst looking for that it got me thinking about maybe changing a lot of my convenience methods to alloc/release. Is there any good reason for doing that? In a large app I can see how releasing memory yourself quickly is a better idea, but in a small app is there any other difference between the two methods. NSNumber *numberToAdd = [NSNumber numberWithInt:intValue]; dostuff ... OR NSNumber *numberToAdd = [[NSNumber alloc] initWithInt:intValue]; doStuff ... [numberToAdd release]; cheers gary.

    Read the article

  • iPhone Development: Get images from RSS feed

    - by Matthew Saeger
    I am using the NSXMLParser to get new RSS stories from a feed and am displaying them in a UITableView. However now I want to take ONLY the images, and display them in a UIScrollView/UIImageView (3 images side-by side). I am completely lost. I am using the following code to obtain 1 image from a URL. NSURL *theUrl1=[NSURL URLWithString:@"http://farm3.static.flickr.com/2586/4072164719_0fa5695f59.jpg"]; JImage *photoImage1=[[JImage alloc] init]; [photoImage1 setContentMode:UIViewContentModeScaleAspectFill]; [photoImage1 setFrame:CGRectMake(0, 0, 320, 170)]; [photoImage1 initWithImageAtURL:theUrl1]; [imageView1 addSubview:photoImage1]; [photoImage1 release]; This is all I have accomplished, and it works, for one image, and I have to specify the exact URL. What would you recommend I do to accomplish this?

    Read the article

  • Regarding xml parsing in iphone

    - by Prash.......
    hi... I am developing an applictaion in which i am doing xml parsing i found an error in [xmlparse parse] method. and the error for this is as follows: [NSCFString bytes]: unrecognized selector sent to instance 0x3df6310 2010-04-30 00:09:46.302 SPCiphone2[4234:1003] void SendDelegateMessage(NSInvocation*): delegate () failed to return after waiting 10 seconds. main run loop mode: kCFRunLoopDefaultMode code snippet for this as follows. responseOfWebResultData = [[NSMutableString alloc] initWithData:responseData encoding:NSUTF8StringEncoding]; NSLog(@"result: %@", responseOfWebResultData); //starting the XML parsing if(responseOfWebResultData) { @try { xmlParser = [[NSXMLParser alloc] initWithData:responseOfWebResultData]; [xmlParser setDelegate: self]; [xmlParser setShouldResolveExternalEntities: YES]; [xmlParser parse]; [responseOfWebResultData release]; } @catch(NSException *e) { UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Please " message:[e reason] delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil]; [alert show]; [alert release]; } }

    Read the article

  • What's the best way to parse RSS/Atom feeds for an iPhone application?

    - by jpm
    So I understand that there are a few options available as far as parsing straight XML goes: NSXMLParser, TouchXML from TouchCode, etc. That's all fine, and seems to work fine for me. The real problem here is that there are dozens of small variations in RSS feeds (and Atom feeds too), so supporting all possible permutations of feeds available out on the Internet gets very difficult to manage. I searched around for a library that would handle all of these low-level details for me, but came out without anything. Since one could link to an external C/C++ library in Objective-C, I was wondering if there is a library out there that would be best suited for this task? Someone must have already created something like this, it's just difficult to find the "right" option from the thousands of results in Google. Anyway, what's the best way to parse RSS/Atom feeds in an iPhone application?

    Read the article

  • How to modify XML on Objective-C?

    - by Vic
    Hi, I'm working on a project for the iPad, I need to read and write to an xml file, which is also used by the counter part of the application in windows. The problem that I have is that I've been looking around but I haven't found a way to modify an element or attribute in an xml, without having to build the whole xml again. I saw this other post, which is basically the same problem that I have, and I also end it up in the same point as the person asking the question, NSXMLParser and TouchXML are read only and do not allowed me to modify my xml. Any other suggestion about what can I use? Thanks!

    Read the article

  • Ideas for loading initial data in an iPhone application?

    - by Derek Clarkson
    Hi all, In my app I want to load some initial data to show the user how it works. The app uses a CoreData managed sqllite db. SO far I've thought of 3 options: Write code into a class to programmatically create the data. Create a xml file in the apps resources and load through a NSXmlParser whose delegate creates the entries in the sqllite db. Same as option #2, but use a json file and bring in a 3rd party lib to read it. Are there other options I have not found yet? and given that I'm talking about perhaps 6 records per table when there are 3 tables, which would you choose?

    Read the article

  • iPhone YouTube Channel App

    - by pki
    What would the steps be to creating an app that connected to YouTube's XML API. Here is my setup currently but it is not working. App Delegate creates object "YTXMLParser" App Delegate calls [parser prepAndPrase]; In Prep and Parse the app initiates a NSURLConnection The app downloads the XML Data using the NSURLConnection well appeneding to NSMutableData The app parses the data with NSXMLParser At the end of each "entry" the app adds the current dictionary to the class. At the beginning of each "entry" the app creates an instance of a dictionary. Here's where i'm stuck. How do I get this data back to my app delegate?

    Read the article

  • How do I use comma-separated-value file received from a URL query in Objective-c?

    - by chiemekailo
    How do I use comma-separated-value file received from a URL query in Objective-c? when I query the URL I get csv such as "OMRUAH=X",20.741,"3/16/2010","1:52pm",20.7226,20.7594. How do I capture and use this for my application? My problem is creating/initializing that NSString object in the first place. An example is this link "http://download.finance.yahoo.com/d/quotes.csv?s=GBPEUR=X&f=sl1d1t1ba&e=.csv" which returns csv. I dont know how to capture this as an object since I cannot use an NSXMLParser object.

    Read the article

  • XML Processing on iPhone: What is the best option?

    - by gonso
    Hello Im building a new version of an iPhone application and Im wondering if I should review how my app communicates with the server. My iPhone client sends and receives XML over HTTP requests. To send the information I use ASIHTTPRequest framework. I "manually" build the XML request by appending strings. To parse the response Im using a NSXMLParser. My question is if I have better options to A) Create an XML string from a memory object. B) Create a memory object from the XML string. Is there anything like JAXB to marshal XML into object? Thanks Gonso

    Read the article

  • My application crashing Please help me out.

    - by kiran kumar
    My Application get crashing ... its loading data of all the cities... and when i click its displaying my detailed view controller.... when iam getting back from my controller... and selecting another city my application get crashed.. Please help me out. To get idea i am pasting my code. #import "CityNameViewController.h" #import "Cities.h" #import "XMLParser.h" #import "PartyTemperature_AppDelegate.h" #import "CityEventViewController.h" @implementation CityNameViewController //@synthesize aCities; @synthesize appDelegate; @synthesize currentIndex; @synthesize aCities; /* // The designated initializer. Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad. - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) { // Custom initialization } return self; } */ // Implement viewDidLoad to do additional setup after loading the view, typically from a nib. - (void)viewDidLoad { [super viewDidLoad]; self.title=@"Cities"; appDelegate=(PartyTemperature_AppDelegate *)[[UIApplication sharedApplication]delegate]; } /* // Override to allow orientations other than the default portrait orientation. - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { // Return YES for supported orientations return (interfaceOrientation == UIInterfaceOrientationPortrait); } */ - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { // Return the number of sections. return 1; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { // Return the number of rows in the section. return [appDelegate.cityListArray count]; } - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { return 95.0f; } - (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath { cell.accessoryType=UITableViewCellAccessoryDisclosureIndicator; cell.textLabel.textColor = [[[UIColor alloc] initWithRed:0.2 green:0.2 blue:0.6 alpha:1] autorelease]; cell.detailTextLabel.textColor = [UIColor blackColor]; cell.detailTextLabel.font=[UIFont systemFontOfSize:10]; if (indexPath.row %2 == 1) { cell.backgroundColor = [[[UIColor alloc] initWithRed:0.87f green:0.87f blue:0.87f alpha:1.0f] autorelease]; } else { cell.backgroundColor = [[[UIColor alloc] initWithRed:0.97f green:0.97f blue:0.97f alpha:1.0f] autorelease]; } } // Customize the appearance of table view cells. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease]; cell.selectionStyle= UITableViewCellSelectionStyleBlue; // cell.accessoryType=UITableViewCellAccessoryDisclosureIndicator; cell.backgroundColor=[UIColor blueColor]; } // aCities=[appDelegate.cityListArray objectAtIndex:indexPath.row]; // cell.textLabel.text=aCities.city_Name; cell.textLabel.text=[[appDelegate.cityListArray objectAtIndex:indexPath.row]city_Name]; return cell; } - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{ //http://compliantbox.com/party_temperature/citysearch.php?city=Amsterdam&latitude=52.366125&longitude=4.899171 NSString *url; aCities=[appDelegate.cityListArray objectAtIndex:indexPath.row]; if ([appDelegate.cityListArray count]>0){ url=@"http://compliantbox.com/party_temperature/citysearch.php?city="; url=[url stringByAppendingString:aCities.city_Name]; url=[url stringByAppendingString:@"&latitude=52.366125&longitude=4.899171"]; NSLog(@"url value is %@",url); [self parseCityName:[[NSURL alloc]initWithString:url]]; } } -(void)parseCityName:(NSURL *)url{ NSXMLParser *xmlParser=[[NSXMLParser alloc]initWithContentsOfURL:url]; XMLParser *parser=[[XMLParser alloc] initXMLParser]; [xmlParser setDelegate:parser]; BOOL success; success=[xmlParser parse]; if (success) { NSLog(@"Sucessfully parsed"); CityEventViewController *cityEventViewController=[[CityEventViewController alloc]initWithNibName:@"CityEventViewController" bundle:nil]; cityEventViewController.index=currentIndex; [self.navigationController pushViewController:cityEventViewController animated:YES]; [cityEventViewController release]; cityEventViewController=nil; } else { NSLog(@"Try it Idoit"); UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"Alert!" message:@"Event Not In Radius" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil]; [alert show]; [alert release]; } } - (void)didReceiveMemoryWarning { // Releases the view if it doesn't have a superview. [super didReceiveMemoryWarning]; // Release any cached data, images, etc that aren't in use. } - (void)viewDidUnload { [super viewDidUnload]; // Release any retained subviews of the main view. // e.g. self.myOutlet = nil; } - (void)dealloc { [aCities release]; [super dealloc]; } @end And the error is * Terminating app due to uncaught exception 'NSRangeException', reason: ' -[NSMutableArray objectAtIndex:]: index 1 beyond bounds for empty array' ** Call stack at first throw:

    Read the article

  • Remove newline character while XML parsing

    - by Prashant
    Hi, I am facing a problem while XML parsing. I have an NSMutablestring currentElementValue that has newlines into it. It has been received as an XMl from a web source. Even when i am trying to remove newline charactersets of substring the first 3 char there is no effect on the string. What can be done here? Regards PC Code is (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string { if(!currentElementValue) currentElementValue = [[NSMutableString alloc] initWithString:string]; else { [currentElementValue substringFromIndex:3]; [currentElementValue stringByTrimmingCharactersInSet:[NSCharacterSet newlineCharacterSet]]; NSLog(@"Processing Value : %@ with length %d", currentElementValue,[currentElementValue length] ); }

    Read the article

  • write to xml file using objective c

    - by Mith
    Hi, ok, I managed to read from xml file using NSXMLParser but now i don't know how to write to xml file. I have a xml file , say <?xml version="1.0" encoding="UTF-8"?> <root> <user id="abcd" password="pass1"/> <user id="efg" password="pass2"/> </root> Now when a new user enters details, I want to store them in a new tag.. lets say like, the id is "hhhh" and password is"pass3" I want to add a new tag with attributes as such <user id="hhhh" password="pass3"/> to the xml file. How should I do this. Please explain in an elaborate way . I am a newbie here. Any links to tutorials or examples will be much helpful. Thanks

    Read the article

  • Base64 en/decoding between xstream and iPhone SDK

    - by Matt McMinn
    I am passing a byte array from a java server to an iPad client in XML. The server is using xstream to convert the byte array to XML with the EncodedByteArrayConverter, which should convert the array to Base 64. Using xstream, I can decode the xml back to the proper byte array in a java client, but in the iPad client, I'm getting an invalid length error. To do my decoding, I'm using the code at the bottom of this page. The length of the string is indeed not a multiple of 4, so there must be something strange with my string - although since xstream can decode it just fine, I'm guessing there's just something I need to to on the iPad side to get it to decode. I've tried cutting off padding at the end of the string to get it down to the right size, and that does allow the decoder to work, but I end up with JPG's that have invalid headers, and are not displayable. On the server side, I'm using the following code: Object rtrn = getByteArray(); XStream xstream = new XStream(); String xml = xstream.toXML(rtrn); On the client side, I'm calling the above decoder from the XML parsing callback like this: -(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string { NSLog(@"Converting data; string length: %d", [string length]); //NSLog(@"%@", string); NSData *data = [Base64 decode:string]; NSLog(@"converted data length: %d", [data length]); } Any ideas what could be going wrong?

    Read the article

  • NULL value when using NSDateFormatter after setting NSDate property via XML parsing

    - by David A Gibson
    Hello, I am using the following code to try and display in a time in a table cell. TimeSlot *timeSlot = [timeSlots objectAtIndex:indexPath.row]; NSDateFormatter *timeFormat = [[NSDateFormatter alloc] init]; [timeFormat setDateFormat:@"HH:mm:ss"]; NSLog(@"Time: %@", timeSlot.time); NSDate *mydate = timeSlot.time; NSLog(@"Time: %@", mydate); NSString *theTime = [timeFormat stringFromDate:mydate]; NSLog(@"Time: %@", theTime); The log output is this: 2010-04-14 10:23:54.626 MyApp[1080:207] Time: 2010-04-14T10:23:54 2010-04-14 10:23:54.627 MyApp[1080:207] Time: 2010-04-14T10:23:54 2010-04-14 10:23:54.627 MyApp[1080:207] Time: (null) I am new to developing for the iPhone and as it all compiles with no errors or warnings I am at a loss as to why I am getting NULL in the log. Is there anything wrong with this code? Thanks Further Info I used the code exactly from your answer lugte098 just to check and I was getting dates which leads me to believe that my TimeSlot class can't have a date correctly set in it's NSDate property. So my question becomes - how from XML do I set a NSDate property? I have this code (abbreviated): -(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *) string { if ([currentElement isEqualToString:@"Time"]) { currentTimeSlot.time = string } } Thanks

    Read the article

  • Memory allocation in detached NSThread to load an NSDictionary in background?

    - by mobibob
    I am trying to launch a background thread to retrieve XML data from a web service. I developed it synchronously - without threads, so I know that part works. Now I am ready to have a non-blocking service by spawning a thread to wait for the response and parse. I created an NSAutoreleasePool inside the thread and release it at the end of the parsing. The code to spawn and the thread are as follows: Spawn from main-loop code: . . [NSThread detachNewThreadSelector:@selector(spawnRequestThread:) toTarget:self withObject:url]; . . Thread (inside 'self'): -(void) spawnRequestThread: (NSURL*) url { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; parser = [[NSXMLParser alloc] initWithContentsOfURL:url]; [self parseContentsOfResponse]; [parser release]; [pool release]; } The method parseContentsOfResponse fills an NSMutableDictionary with the parsed document contents. I would like to avoid moving the data around a lot and allocate it back in the main-loop that spawned the thread rather than making a copy. First, is that possible, and if not, can I simply pass in an allocated pointer from the main thread and allocate with 'dictionaryWithDictionary' method? That just seems so inefficient. Are there perferred designs?

    Read the article

  • Parsing XHTML with inline tags

    - by user290796
    Hi, I'm trying to parse an XHTML document using TBXML on the iPhone (although I would be happy to use either libxml2 or NSXMLParser if it would be easier). I need to extract the content of the body as a series of paragraphs and maintain the inline tags, for example: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"> <head> <title>Title</title> <link rel="stylesheet" href="css/style.css" type="text/css"/> <meta http-equiv="Content-Type" content="application/xhtml+xml; charset=utf-8"/> </head> <body> <div class="body"> <div> <h3>Title</h3> <p>Paragraph with <em>inline</em> tags</p> <img src="image.png" /> </div> </div> </body> </html> I need to extract the paragraph but maintain the <em>inline</em> content with the paragraph, all my testing so far has extracted that as a subelement without me knowing exactly where it fitted in the paragraph. Can anyone suggest a way to do this? Thanks.

    Read the article

  • What is the best way to properly test object equality against an array of objects?

    - by radesix
    My objective is to abort the NSXMLParser when I parse an item that already exists in cache. The basic flow of the program works like this: 1) Program starts and downloads an XML feed. Each item in the feed is represented by a custom object (FeedItem). Each FeedItem gets added to an array. 2) When the parsing is complete the contents of the array (all FeedItem objects) are archived to the disk. The next time the program is executed or the feed is refreshed by the user I begin parsing again; however, since a cache (array) now exists as each item is parsed I want to see if the object exists in the cache. If it does then I know I have downloaded all the new items and no longer need to continue parsing. What I am learning, I think, is that I can't use indexOfObject or indexOfObjectIDenticalTo: because these really seem to be checking to see that the objects are using the same memory address (thus identical). What I want to do is see if the contents of the object are equal (or at least some of the contents). I've done some research and found that I can override the IsEqual method; however, I really don't want to iterate/enumerate through the entire cache contents table for every newly parsed XML FeedItem. Is iterating through the collection and testing each one for equality the only way to do this or is there a better technique I am not aware of? Currently I am using the following code though I know it needs to change: NSUInteger index = [self.feedListCache.feedList indexOfObject:self.currentFeedItem]; if (index == NSNotFound) { }

    Read the article

  • Why does my UIActivityIndicatorView only display once?

    - by Schwigg
    I'm developing an iPhone app that features a tab-bar based navigation with five tabs. Each tab contains a UITableView whose data is retrieved remotely. Ideally, I would like to use a single UIActivityIndicatorView (a subview of the window) that is started/stopped during this remote retrieval - once per tab. Here's how I set up the spinner in the AppDelegate: - (void)applicationDidFinishLaunching:(UIApplication *)application { [window addSubview:rootController.view]; activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge]; [activityIndicator setCenter:CGPointMake(160, 200)]; [window addSubview:activityIndicator]; [window makeKeyAndVisible]; } Since my tabs were all performing a similiar function, I created a base class that all of my tabs' ViewControllers inherit from. Here is the method I'm using to do the remote retrieval: - (void)parseXMLFileAtURL:(NSString *)URL { NSAutoreleasePool *apool = [[NSAutoreleasePool alloc] init]; AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate]; NSLog(@"parseXMLFileAtURL started."); [appDelegate.activityIndicator startAnimating]; NSLog(@"appDelegate.activityIndicator: %@", appDelegate.activityIndicator); articles = [[NSMutableArray alloc] init]; NSURL *xmlURL = [NSURL URLWithString:URL]; rssParser = [[NSXMLParser alloc] initWithContentsOfURL:xmlURL]; [rssParser setDelegate:self]; [rssParser setShouldProcessNamespaces:NO]; [rssParser setShouldReportNamespacePrefixes:NO]; [rssParser setShouldResolveExternalEntities:NO]; [rssParser parse]; NSLog(@"parseXMLFileAtURL finished."); [appDelegate.activityIndicator stopAnimating]; [apool release]; } This method is being called by each view controller as follows: - (void)viewDidAppear:(BOOL)animated { [super viewDidAppear:animated]; if ([articles count] == 0) { NSString *path = @"http://www.myproject.com/rss1.xml"; [self performSelectorInBackground:@selector(parseXMLFileAtURL:) withObject:path]; } } This works great while the application loads the first tab's content. I'm presented with the empty table and the spinner. As soon as the content loads, the spinner goes away. Strangely, when I click the second tab, the NSLog messages from the -parseXMLFileAtURL: method show up in the log, but the screen hangs on the first tab's view and I do not see the spinner. As soon as the content is done downloading, the second tab's view appears. I suspect this has something to do with threading, with which I'm still becoming acquainted. Am I doing something obviously wrong here?

    Read the article

  • iPhone Crash Report

    - by skywalker168
    My iPhone app is crashing for certain users in UK. I tried using UK timezone and their region format but couldn't reproduce the crash on my iPhone or emulator. Eventually got a crash report and I was able to symbolicate it. However, I have a hard time understanding the results. It appears thread 0 crashed in a system library. The only call from my app is main.m. Thread 4 has something familiar. It was at: My App 0x00004cca -[TocTableController parser:didEndElement:namespaceURI:qualifiedName:] (TocTableController.m:1369) Code is: NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease]; It crashed doing alloc/init? Out of memory, only in UK? Any one has idea what might be cause? Thanks in advance! Date/Time: 2010-04-06 21:41:17.629 +0100 OS Version: iPhone OS 3.1.3 (7E18) Report Version: 104 Exception Type: EXC_CRASH (SIGABRT) Exception Codes: 0x00000000, 0x00000000 Crashed Thread: 0 Thread 0 Crashed: 0 libSystem.B.dylib 0x00090b2c __kill + 8 1 libSystem.B.dylib 0x00090b1a kill + 4 2 libSystem.B.dylib 0x00090b0e raise + 10 3 libSystem.B.dylib 0x000a7e34 abort + 36 4 libstdc++.6.dylib 0x00066390 __gnu_cxx::__verbose_terminate_handler() + 588 5 libobjc.A.dylib 0x00008898 _objc_terminate + 160 6 libstdc++.6.dylib 0x00063a84 __cxxabiv1::__terminate(void (*)()) + 76 7 libstdc++.6.dylib 0x00063afc std::terminate() + 16 8 libstdc++.6.dylib 0x00063c24 __cxa_throw + 100 9 libobjc.A.dylib 0x00006e54 objc_exception_throw + 104 10 Foundation 0x0000202a __NSThreadPerformPerform + 574 11 CoreFoundation 0x000573a0 CFRunLoopRunSpecific + 1908 12 CoreFoundation 0x00056c18 CFRunLoopRunInMode + 44 13 GraphicsServices 0x000041c0 GSEventRunModal + 188 14 UIKit 0x00003c28 -[UIApplication _run] + 552 15 UIKit 0x00002228 UIApplicationMain + 960 16 My App 0x00002414 main (main.m:14) 17 My App 0x000023e4 start + 32 Thread 1: 0 libSystem.B.dylib 0x00001488 mach_msg_trap + 20 1 libSystem.B.dylib 0x00004064 mach_msg + 60 2 CoreFoundation 0x00057002 CFRunLoopRunSpecific + 982 3 CoreFoundation 0x00056c18 CFRunLoopRunInMode + 44 4 WebCore 0x000841d4 RunWebThread(void*) + 412 5 libSystem.B.dylib 0x0002b780 _pthread_body + 20 Thread 2: 0 libSystem.B.dylib 0x00001488 mach_msg_trap + 20 1 libSystem.B.dylib 0x00004064 mach_msg + 60 2 CoreFoundation 0x00057002 CFRunLoopRunSpecific + 982 3 CoreFoundation 0x00056c18 CFRunLoopRunInMode + 44 4 Foundation 0x0005a998 +[NSURLConnection(NSURLConnectionReallyInternal) _resourceLoadLoop:] + 172 5 Foundation 0x00053ac6 -[NSThread main] + 42 6 Foundation 0x00001d0e __NSThread__main__ + 852 7 libSystem.B.dylib 0x0002b780 _pthread_body + 20 Thread 3: 0 libSystem.B.dylib 0x000262c0 select$DARWIN_EXTSN + 20 1 CoreFoundation 0x000207e2 __CFSocketManager + 342 2 libSystem.B.dylib 0x0002b780 _pthread_body + 20 Thread 4: 0 libSystem.B.dylib 0x00015764 fegetenv + 0 1 libSystem.B.dylib 0x0002a160 time + 8 2 libicucore.A.dylib 0x00009280 uprv_getUTCtime + 6 3 libicucore.A.dylib 0x0000a492 icu::Calendar::getNow() + 2 4 libicucore.A.dylib 0x0000a2a0 icu::GregorianCalendar::GregorianCalendar(icu::Locale const&, UErrorCode&) + 86 5 libicucore.A.dylib 0x0000a242 icu::GregorianCalendar::GregorianCalendar(icu::Locale const&, UErrorCode&) + 2 6 libicucore.A.dylib 0x000098ec icu::Calendar::createInstance(icu::TimeZone*, icu::Locale const&, UErrorCode&) + 160 7 libicucore.A.dylib 0x00008762 icu::SimpleDateFormat::initializeCalendar(icu::TimeZone*, icu::Locale const&, UErrorCode&) + 28 8 libicucore.A.dylib 0x0000bd2c icu::SimpleDateFormat::SimpleDateFormat(icu::Locale const&, UErrorCode&) + 82 9 libicucore.A.dylib 0x0000bcd2 icu::SimpleDateFormat::SimpleDateFormat(icu::Locale const&, UErrorCode&) + 2 10 libicucore.A.dylib 0x000084aa icu::DateFormat::create(icu::DateFormat::EStyle, icu::DateFormat::EStyle, icu::Locale const&) + 148 11 libicucore.A.dylib 0x0000840e icu::DateFormat::createDateTimeInstance(icu::DateFormat::EStyle, icu::DateFormat::EStyle, icu::Locale const&) + 14 12 libicucore.A.dylib 0x00008336 udat_open + 70 13 CoreFoundation 0x0006c2e0 CFDateFormatterCreate + 252 14 Foundation 0x00019fd2 -[NSDateFormatter _regenerateFormatter] + 198 15 Foundation 0x00019ebe -[NSDateFormatter init] + 150 16 My App 0x00004cca -[TocTableController parser:didEndElement:namespaceURI:qualifiedName:] (TocTableController.m:1369) 17 Foundation 0x000380e6 _endElementNs + 442 18 libxml2.2.dylib 0x00011d2c xmlParseXMLDecl + 1808 19 libxml2.2.dylib 0x0001ef08 xmlParseChunk + 3300 20 Foundation 0x0003772a -[NSXMLParser parse] + 178 21 My App 0x000055e2 -[TocTableController parseTocData:] (TocTableController.m:1120) 22 Foundation 0x00053ac6 -[NSThread main] + 42 23 Foundation 0x00001d0e __NSThread__main__ + 852 24 libSystem.B.dylib 0x0002b780 _pthread_body + 20 Thread 0 crashed with ARM Thread State: r0: 0x00000000 r1: 0x00000000 r2: 0x00000001 r3: 0x384e83cc r4: 0x00000006 r5: 0x001d813c r6: 0x2ffff2b8 r7: 0x2ffff2c8 r8: 0x38385cac r9: 0x0000000a r10: 0x0002c528 r11: 0x0012be50 ip: 0x00000025 sp: 0x2ffff2c8 lr: 0x33b3db21 pc: 0x33b3db2c cpsr: 0x00070010

    Read the article

< Previous Page | 1 2 3 4 5 6  | Next Page >