Search Results

Search found 605 results on 25 pages for 'stringwithformat'.

Page 3/25 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • Calculation Conundrum - how do I influence another textfield?

    - by LawVS
    Hey! Basically I have a problem in that when certain parameters are used in my calculator app - it makes the result incorrect. The issue is that I have separate text fields for hours and minutes and say for example I have as the start time "13" in one text field and "30" in the other with the finish time "24" and "00" in their respective text fields. The answer should be 10 hours 30 minutes, but the answer I get is 11 hours 30 minutes. The code for this is the following. -(IBAction)done:(id)sender { int result = [finishHours.text intValue] - [startHours.text intValue]; totalHours.text = [NSString stringWithFormat:@"%d", result]; if (result < 0) { totalHours.text = [NSString stringWithFormat:@"%d", result + 24]; } -(IBAction)done2:(id)sender { int result = [startMinutes.text intValue] - [finishMinutes.text intValue]; totalMinutes.text = [NSString stringWithFormat:@"%d", result]; if (result < 0) { totalMinutes.text = [NSString stringWithFormat:@"%d", result + 60]; } } I want to make it so if certain parameters are met, then the totalHours.text is reduced by 1 hour to reflect the total minutes. How would I go about that calculation in code? Thanks!

    Read the article

  • Append data to file in iPhone app

    - by zp26
    I have a problem. I want to create a file like XML. I have create a code for this but the file not append the information but rewrite and save only the last NSData. Can you help me/ This is my code -(void)salvataggioInXML:(NSString*)name:(float)x:(float)y:(float)z{ NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectoryPath = [paths objectAtIndex:0]; NSString *filePath = [documentsDirectoryPath stringByAppendingPathComponent:@"filePosizioni.xml"]; NSFileHandle *myHandle = [NSFileHandle fileHandleForUpdatingAtPath:filePath]; [myHandle seekToEndOfFile]; NSString *tagName = [NSString stringWithFormat:@"<name>%@<name>", name]; NSString *tagX = [NSString stringWithFormat:@"<x>%f<x>", name]; NSString *tagY = [NSString stringWithFormat:@"<y>%f<y>", name]; NSString *tagZ = [NSString stringWithFormat:@"<z>%f<z>", name]; NSData* dataName = [tagName dataUsingEncoding: NSASCIIStringEncoding]; NSData* dataX = [tagX dataUsingEncoding: NSASCIIStringEncoding]; NSData* dataY = [tagY dataUsingEncoding: NSASCIIStringEncoding]; NSData* dataZ = [tagZ dataUsingEncoding: NSASCIIStringEncoding]; if ([dataName writeToFile:filePath atomically:YES]) NSLog(@"writeok"); [myHandle seekToEndOfFile]; if ([dataX writeToFile:filePath atomically:YES]) NSLog(@"writeok"); [myHandle seekToEndOfFile]; if ([dataY writeToFile:filePath atomically:YES]) NSLog(@"writeok"); [myHandle seekToEndOfFile]; if ([dataZ writeToFile:filePath atomically:YES]) NSLog(@"writeok"); [myHandle seekToEndOfFile]; NSLog(@"zp26 %@",filePath); }

    Read the article

  • iPod library song path access

    - by Narendra Kumar
    I studied a lot but did not find any good answer. My problem is i am calculating beats per minute of song.I used Bass api for that, now problem is i am able to get bpm of a file which i have in my resource folder but i have to get bpm of all songs of iPod library. I am getting path of song from MPMediaItemPropertyAssetURL property of MpMediaItem but when passing this one in api api is saying stream cant load BASS_StreamCreateFile(). In my point of view i am not getting right path of song. How can we access valid path? Did any one access ipod library song with external api? Please help me . Thanks CODE IS THIS NSURL *assetURL = [song valueForProperty:MPMediaItemPropertyAssetURL]; NSString *respath = [NSString stringWithFormat:@"%@",[assetURL absoluteString]]; BASS_SetConfig(BASS_CONFIG_IOS_MIXAUDIO, 0); // Disable mixing. To be called before BASS_Init. if (HIWORD(BASS_GetVersion()) != BASSVERSION) { NSLog(@"An incorrect version of BASS was loaded"); } // Initialize default device. if (!BASS_Init(-1, 44100, 0, NULL, NULL)) { //textView.text = [NSString stringWithFormat:@"%@ CAN'T Load Stream",textView.text]; } DWORD chan1; if(!(chan1=BASS_StreamCreateFile(FALSE, [respath UTF8String], 0, 0, BASS_SAMPLE_LOOP))) { NSLog(@"Can't load stream!"); textView.text = [NSString stringWithFormat:@"%@ not loading...",textView.text]; } mainStream=BASS_StreamCreateFile(FALSE, [respath cStringUsingEncoding:NSUTF8StringEncoding], 0, 0, BASS_SAMPLE_FLOAT|BASS_STREAM_PRESCAN|BASS_STREAM_DECODE); float playBackDuration=BASS_ChannelBytes2Seconds(mainStream, BASS_ChannelGetLength(mainStream, BASS_POS_BYTE)); NSLog(@"Play back duration is %f",playBackDuration); HSTREAM bpmStream=BASS_StreamCreateFile(FALSE, [respath UTF8String], 0, 0, BASS_STREAM_PRESCAN|BASS_SAMPLE_FLOAT|BASS_STREAM_DECODE); //BASS_ChannelPlay(bpmStream,FALSE); BpmValue= BASS_FX_BPM_DecodeGet(bpmStream,0.0, playBackDuration, MAKELONG(45,256), BASS_FX_BPM_MULT2| BASS_FX_BPM_MULT2 | BASS_FX_FREESOURCE, (BPMPROCESSPROC*)proc); textView.text = [NSString stringWithFormat:@"%@ %f",textView.text,BpmValue];

    Read the article

  • SQLITE crash when no data present in table

    - by johnblack45
    Hey, Im having a problem with my app that causes it to crash when no data is present in the table when using a table view. I have tested my code and it works fine as long as there is data present but i need it to work when there is no data present. -(void)initialiseTableData { NSMutableArray *array = [[NSMutableArray alloc]init]; sqlite3 *db = [iCaddyAppDelegate getNewDBConnection]; sqlite3_stmt *statement; const char *sql = "select courseId, courseName, totalPar, totalyardage, holePars, holeYardages, holeStrokeIndexs from Course"; if(sqlite3_prepare_v2(db, sql, -1, &statement, NULL)!= SQLITE_OK) { NSAssert1(0,@"Error preparing statement",sqlite3_errmsg(db)); sqlite3_close(db); } else { while (sqlite3_step(statement) == SQLITE_ROW) { Course *temp = [[Course alloc]init]; temp.courseId = sqlite3_column_int(statement,0); temp.courseName = [NSString stringWithFormat:@"%s",(char*)sqlite3_column_text(statement,1)]; temp.totalPar =sqlite3_column_int(statement,2); temp.totalYardage =sqlite3_column_int(statement,3); NSString tempHolePars = [NSString stringWithFormat:@"%s",(char)sqlite3_column_text(statement,4)]; NSString tempHoleYardages = [NSString stringWithFormat:@"%s",(char)sqlite3_column_text(statement,5)]; NSString tempHoleStrokeIndexes = [NSString stringWithFormat:@"%s",(char)sqlite3_column_text(statement,6)]; NSArray *temp1 = [tempHolePars componentsSeparatedByString:@":"]; NSArray *temp2 = [tempHoleYardages componentsSeparatedByString:@":"]; NSArray *temp3 = [tempHoleStrokeIndexes componentsSeparatedByString:@":"]; for(int i = 0; i<=17; i++) { NSString *temp1String = [temp1 objectAtIndex:i]; [temp.holePars insertObject:temp1String atIndex:i]; NSString *temp2String = [temp2 objectAtIndex:i]; [temp.holeYardages insertObject:temp2String atIndex:i]; NSString *temp3String = [temp3 objectAtIndex:i]; [temp.holeStrokeIndexes insertObject:temp3String atIndex:i]; } [array addObject:temp]; } self.list = array; [self.table reloadData]; } }

    Read the article

  • Uploadin Image - Objective C

    - by Sammaeliv
    Hi, i have this code the i find on youtube xD my cuestion is , how do i add an extra parameter NSData *imageData = UIImageJPEGRepresentation(imagen.image,0.0); NSString *urlString = @"http://urlexample.com/upload.php"; NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease]; [request setURL:[NSURL URLWithString:urlString]]; [request setHTTPMethod:@"POST"]; NSString *boundary = [NSString stringWithString:@"---------------------------14737809831466499882746641449"]; NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary]; [request addValue:contentType forHTTPHeaderField:@"Content-Type"]; NSMutableData *body = [NSMutableData data]; [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[[NSString stringWithString:@"Content-Disposition: form-data; name=\"userfile\"; filename=\".jpg\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[NSData dataWithData:imageData]]; [body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]]; [request setHTTPBody:body]; NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil]; NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding]; NSLog(returnString); I try [body appendData:[[NSString stringWithFormat:@"extra=%@",info] dataUsingEncoding:NSUTF8StringEncoding]; hehehe im 100% new on this as you can see... please help me xD

    Read the article

  • game currency convert: math efficient

    - by Comradsky
    For variables:4 text views named diamondText, goldText, silverText, and bronzeText;money variable unsigned int money;and an NSTimer, every .1 sec,runs function: -(void)updateMoney{ money++; bronzeText.text = [NSString stringWithFormat:@"%d",money]; silverText.text = [NSString stringWithFormat:@"%d",money%10]; goldText.text = [NSString stringWithFormat:@"%d",money%100]; diamondText.text= [NSString stringWithFormat:@"%d",money%1000]; } Given that my currency is diamond = 10 gold = 10 silver = 10 bronze = 1; What would be most efficient way to calculate and display the money labels? How would you store this variable, with GameCenter and NSDictionary or GameCenter and something else? More details are below if you don't understand. To clarify: bronze has the last 2 numbers, silver has the next 2 numbers, and so on. I understand I could use 4 ints or an array, but i would rather try to use this method, unless theres a much more efficient way. Example: When money = 1000;bronzeText = nothing, silverText = 10,goldText = nothing, diamondText = nothing; What other ways would you do this that you think would be more efficient? I will be calling a function (void)collisionDetector that detects if my player.frame crosses with a flyingObject.frame, and if that object is a coin it gives an added value to money and then calls (void)updateMoney. Im just using the timer to test this and spawn these flying objects.

    Read the article

  • Xcode is not calling asp.net webservice

    - by vaibhav
    I have oracle database and using webservice i want to insert some records in to it So i created webservice in asp.net as follows public bool PickPill(string Me_id, string Mem_device_id, string Test_datetime, string Creation_id, string PillBayNo) { string Hed_seq_id = Hed_seq_Id(); bool ResultHED = InsHealthEData(Hed_seq_id, Mem_device_id, Me_id, Test_datetime, Creation_id); bool ResultHET = InsHealthETest(Hed_seq_id, PillBayNo, Test_datetime, Creation_id); if (ResultHED == ResultHET == true) return true; else return false; } this function did all data insertion trick for me i tested this service on the local mechine with ip address http:72.44.151.178/PickPillService.asmx then, I see an example on how to attach asp.net web service to iphone apps http://www.devx.com/wireless/Article/43209/0/page/4 then i created simillar code in xcode which has 2 files ConsumePillServiceViewController.m ConsumePillServiceViewController.h file Now, Using Designer of xcode i created 5 textboxes(Me_id,Mem_device_id,Test_datetime,Creation_id,PillBayNo) with all parameters hardcode as our service demands then modify my ConsumePillServiceViewController.h file as follows @interface ConsumePillServiceViewController : UIViewController { //---outlets--- IBOutlet UITextField *Me_id; IBOutlet UITextField *Mem_device_id; IBOutlet UITextField *Test_datetime; IBOutlet UITextField *Creation_id; IBOutlet UITextField *PillBayNo; //---web service access--- NSMutableData *webData; NSMutableString *soapResults; NSURLConnection *conn; } @property (nonatomic, retain) UITextField *Me_id; @property (nonatomic, retain) UITextField *Mem_device_id; @property (nonatomic, retain) UITextField *Test_datetime; @property (nonatomic, retain) UITextField *Creation_id; @property (nonatomic, retain) UITextField *PillBayNo; - (IBAction)buttonClicked:(id)sender; @end and ConsumePillServiceViewController.m as follows import "ConsumePillServiceViewController.h" @implementation ConsumePillServiceViewController @synthesize Me_id; @synthesize Mem_device_id; @synthesize Test_datetime; @synthesize Creation_id; @synthesize PillBayNo; (IBAction)buttonClicked:(id)sender { NSString *soapMsg = @"" "" "" ""; NSString *smMe_id= [soapMsg stringByAppendingString: [NSString stringWithFormat: @"%@",Me_id.text]]; NSString *smMem_device_id= [smMe_id stringByAppendingString: [NSString stringWithFormat: @"%@",Mem_device_id.text]]; NSString *smTest_datetime= [smMem_device_id stringByAppendingString: [NSString stringWithFormat: @"%@",Test_datetime.text]]; NSString *smCreation_id= [smTest_datetime stringByAppendingString: [NSString stringWithFormat: @"%@",Creation_id.text]]; NSString *smPillBayNo= [smCreation_id stringByAppendingString: [NSString stringWithFormat: @"%@",PillBayNo.text]]; NSString *smRestMsg= [smPillBayNo stringByAppendingString: @"" "" ""]; soapMsg=smRestMsg; //---print it to the Debugger Console for verification--- NSLog(soapMsg); NSURL *url = [NSURL URLWithString: //create a URL load request object using instances : @"http://72.44.151.178/PickPillService.asmx"];//of the NSMutableURLRequest and NSURL objects NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url]; //opulate the request object with the various headers, such as Content-Type, SOAPAction, and Content-Length. //You also set the HTTP method and HTTP body NSString *msgLength = [NSString stringWithFormat:@"%d", [soapMsg length]]; [req addValue:@"text/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"]; [req addValue:@"http://tempuri.org/PickPill" forHTTPHeaderField:@"SOAPAction"]; [req addValue:msgLength forHTTPHeaderField:@"Content-Length"]; //---set the HTTP method and body--- [req setHTTPMethod:@"POST"]; [req setHTTPBody: [soapMsg dataUsingEncoding:NSUTF8StringEncoding]]; conn = [[NSURLConnection alloc] initWithRequest:req delegate:self]; //establish the connection with the web service, if (conn) { //you use the NSURLConnection class together with the request object just created webData = [[NSMutableData data] retain];//webData object use to receive incoming data from the web service } }//End of button clicked event -(void) connection:(NSURLConnection *) connection //Recive response didReceiveResponse:(NSURLResponse *) response { [webData setLength: 0]; } -(void) connection:(NSURLConnection *) connection //Repeative call method and append data to webData didReceiveData:(NSData *) data { [webData appendData:data]; } -(void) connection:(NSURLConnection *) connection//If error occure error should be displayed didFailWithError:(NSError *) error { [webData release]; [connection release]; } -(void) connectionDidFinishLoading:(NSURLConnection *) connection { NSLog(@"DONE. Received Bytes: %d", [webData length]); NSString *theXML = [[NSString alloc] initWithBytes: [webData mutableBytes] length:[webData length] encoding:NSUTF8StringEncoding]; //---shows the XML--- NSLog(theXML); [connection release]; [webData 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 { // Release any retained subviews of the main view. // e.g. self.myOutlet = nil; } (void)dealloc { [Me_id release]; [Creation_id release]; [Mem_device_id release]; [Test_datetime release]; [PillBayNo release]; [soapResults release]; [super dealloc]; } @end I did all things as shown in the website and when i built application it successfully built but in the debuggin window i see (gdb) continue 2010-03-17 09:09:54.595 ConsumePillService[6546:20b] A00000004303101103/13/2010 07:34:38Hboxdata2 (gdb) continue (gdb) continue (gdb) continue 2010-03-17 09:10:05.411 ConsumePillService[6546:20b] DONE. Received Bytes: 476 2010-03-17 09:10:05.412 ConsumePillService[6546:20b] soap:ServerServer was unable to process request. ---> One or more errors occurred during processing of command. ORA-00936: missing expression It should return me true if all things are ok What is this ORA-00936 error all about as it is not releted with webservice Please help me solving this problem Thanks in advance, Vaibhav Deshpande

    Read the article

  • NSAlert doesn't work

    - by Marco
    Hello i have implemented the following NSAlert: NSString *title = [NSString stringWithFormat:@"Keine Internetverbindung"]; NSString *alertMessage = [NSString stringWithFormat:@"Es konnte keine Verbindung zu www.sip.de aufgebaut werden!"]; NSString *ok = [NSString stringWithFormat:@"Ok"]; UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title message:alertMessage delegate:self cancelButtonTitle:ok otherButtonTitles:nil]; [alert show]; [alert release]; and this is the delegate method to close the app: - (void)alertView:(UIAlertView *)alertView didDisMissWithButtonIndex:(NSInteger)buttonIndex{ exit(3); } But why the programm doesn't go into the method, what is my mistake? greetings Marco

    Read the article

  • does the accelerometer work for the iphone/ipad simulator?

    - by Mark
    From what I can tell, my app should be firing accelerometer events while Im using the iPad simulator in XCode, but its not. I have googled around and it somewhat seems that the accelerometer is not implemented in the simulator, is this correct? If so, why on earth would they have a "Hardware-Shake Gesture" menu option? My code is as follows: .h file: @interface MyViewController : UIViewController <UIPickerViewDataSource, UIPickerViewDelegate, UIAccelerometerDelegate>{ UIAccelerometer *accelerometer; //...other stuff } @property (nonatomic, retain) UIAccelerometer *accelerometer; @end then the .m file: @implementation MyViewController @synthesize accelerometer; - (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration { NSLog(@"%@", [NSString stringWithFormat:@"%@%f", @"X: ", acceleration.x]); NSLog(@"%@", [NSString stringWithFormat:@"%@%f", @"Y: ", acceleration.y]); NSLog(@"%@", [NSString stringWithFormat:@"%@%f", @"Z: ", acceleration.z]); } - (void)viewDidLoad { [super viewDidLoad]; self.accelerometer = [UIAccelerometer sharedAccelerometer]; self.accelerometer.updateInterval = .1; self.accelerometer.delegate = self; } @end Does this look right?

    Read the article

  • iPhone: NSAlert Delegate Method Never Called

    - by Marco
    Hello, I have implemented an NSAlert but the delegate method didDissmissWithButton is never called. This code evokes the NSAlert: NSString *title = [NSString stringWithFormat:@"Keine Internetverbindung"]; NSString *alertMessage = [NSString stringWithFormat:@"Es konnte keine Verbindung zu www.sip.de aufgebaut werden!"]; NSString *ok = [NSString stringWithFormat:@"Ok"]; UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title message:alertMessage delegate:self cancelButtonTitle:ok otherButtonTitles:nil]; [alert show]; [alert release]; and this is the NSAlert delegate method: - (void)alertView:(UIAlertView *)alertView didDisMissWithButtonIndex:(NSInteger)buttonIndex{ exit(3); } The method is never called, what is my mistake?

    Read the article

  • Emailing HTML from within an iPhone app is stopping at special characters

    - by user141146
    Hi, I have an iPhone app that will let users email some pre-determined text as HTML. I'm having a problem in that if the text contains special characters within the text (e.g., ampersand &, , <), the NSString variable that I use for sending the body of the email gets truncated at the special character. I'm not sure how to fix this (I tried using the method stringByAddingPercentEscapesUsingEncoding…but this hasn't fixed the problems). Thoughts on what I'm doing wrong / how to fix it? Here is sample code showing what I'm trying to do Thanks!!! - (void)send_an_email:(id)sender { NSString *subject_string = [NSString stringWithFormat:@"Summary of %@", commercial_name]; NSString *body_string = [NSString stringWithFormat:@"%@<br /><br />", [self.dl email_message]]; // email_message returns the body of text that should be shipped as html. If email_message contains special characters, the text truncates at the special character NSString *full_string = [NSString stringWithFormat:@"mailto:?to=&subject=%@&body=%@", [subject_string stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding], [body_string stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]; [[UIApplication sharedApplication] openURL:[[NSURL alloc] initWithString:full_string]]; }

    Read the article

  • Core Plot: only works ok with three plots

    - by Luis
    I am adding a scatter plot to my app (iGear) so when the user selects one, two or three chainrings combined with a cogset on a bike, lines will show the gears meters. The problem is that Core Plot only shows the plots when three chainrings are selected. I need your help, this is my first try at Core Plot and I'm lost. My code is the following: iGearMainViewController.m - (IBAction)showScatterIpad:(id)sender { cogsetToPass = [NSMutableArray new]; arrayForChainringOne = [NSMutableArray new]; arrayForChainringTwo = [NSMutableArray new]; arrayForChainringThree = [NSMutableArray new]; //behavior according to number of chainrings switch (self.segmentedControl.selectedSegmentIndex) { case 0: // one chainring selected for (int i = 1; i<= [cassette.numCogs intValue]; i++) { if (i <10) { corona = [NSString stringWithFormat:@"cog0%d",i]; }else { corona = [NSString stringWithFormat:@"cog%d",i]; } float one = (wheelSize*[_oneChainring.text floatValue]/[[cassette valueForKey:corona]floatValue])/1000; float teeth = [[cassette valueForKey:corona] floatValue]; [cogsetToPass addObject:[NSNumber numberWithFloat:teeth]]; [arrayForChainringOne addObject:[NSNumber numberWithFloat:one]]; } break; case 1: // two chainrings selected for (int i = 1; i<= [cassette.numCogs intValue]; i++) { if (i <10) { corona = [NSString stringWithFormat:@"cog0%d",i]; }else { corona = [NSString stringWithFormat:@"cog%d",i]; } float one = (wheelSize*[_oneChainring.text floatValue]/[[cassette valueForKey:corona]floatValue])/1000; //NSLog(@" gearsForOneChainring = %@",[NSNumber numberWithFloat:one]); float two = (wheelSize*[_twoChainring.text floatValue]/[[cassette valueForKey:corona]floatValue])/1000; [cogsetToPass addObject:[NSNumber numberWithFloat:[[cassette valueForKey:corona]floatValue]]]; [arrayForChainringOne addObject:[NSNumber numberWithFloat:one]]; [arrayForChainringTwo addObject:[NSNumber numberWithFloat:two]]; } break; case 2: // three chainrings selected for (int i = 1; i<= [cassette.numCogs intValue]; i++) { if (i <10) { corona = [NSString stringWithFormat:@"cog0%d",i]; }else { corona = [NSString stringWithFormat:@"cog%d",i]; } float one = (wheelSize*[_oneChainring.text floatValue]/[[cassette valueForKey:corona]floatValue])/1000; float two = (wheelSize*[_twoChainring.text floatValue]/[[cassette valueForKey:corona]floatValue])/1000; float three = (wheelSize*[_threeChainring.text floatValue]/[[cassette valueForKey:corona]floatValue])/1000; [cogsetToPass addObject:[cassette valueForKey:corona]]; [arrayForChainringOne addObject:[NSNumber numberWithFloat:one]]; [arrayForChainringTwo addObject:[NSNumber numberWithFloat:two]]; [arrayForChainringThree addObject:[NSNumber numberWithFloat:three]]; } default: break; } ScatterIpadViewController *sivc = [[ScatterIpadViewController alloc]initWithNibName: @"ScatterIpadViewController" bundle:nil]; [sivc setModalTransitionStyle:UIModalTransitionStyleFlipHorizontal]; sivc.records = [cassetteNumCogs integerValue]; sivc.cogsetSelected = self.cogsetToPass; sivc.chainringOne = self.arrayForChainringOne; sivc.chainringThree = self.arrayForChainringThree; sivc.chainringTwo = self.arrayForChainringTwo; [self presentViewController:sivc animated:YES completion:nil]; } And the child view with the code to draw the plots: ScatterIpadViewController.m #pragma mark - CPTPlotDataSource methods - (NSUInteger)numberOfRecordsForPlot: (CPTPlot *)plot { return records; } - (NSNumber *)numberForPlot: (CPTPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index{ switch (fieldEnum) { case CPTScatterPlotFieldX: return [NSNumber numberWithInt:index]; break; case CPTScatterPlotFieldY:{ if ([plot.identifier isEqual:@"one"]==YES) { //NSLog(@"chainringOne objectAtIndex:index = %@", [chainringOne objectAtIndex:index]); return [chainringOne objectAtIndex:index]; }else if ([plot.identifier isEqual:@"two"] == YES ){ //NSLog(@"chainringTwo objectAtIndex:index = %@", [chainringTwo objectAtIndex:index]); return [chainringTwo objectAtIndex:index]; }else if ([plot.identifier isEqual:@"three"] == YES){ //NSLog(@"chainringThree objectAtIndex:index = %@", [chainringThree objectAtIndex:index]); return [chainringThree objectAtIndex:index]; } default: break; } } return nil; } The error returned is an exception on trying to access an empty array. 2012-11-15 11:02:42.962 iGearScatter[3283:11603] Terminating app due to uncaught exception 'NSRangeException', reason: ' -[__NSArrayM objectAtIndex:]: index 0 beyond bounds for empty array' First throw call stack: (0x1989012 0x1696e7e 0x192b0b4 0x166cd 0x183f4 0x1bd39 0x179c0 0x194fb 0x199e1 0x43250 0x14b66 0x13ef0 0x13e89 0x3b5753 0x3b5b2f 0x3b5d54 0x3c35c9 0x5c0814 0x392594 0x39221c 0x394563 0x3103b6 0x310554 0x1e87d8 0x27b3014 0x27a37d5 0x192faf5 0x192ef44 0x192ee1b 0x29ea7e3 0x29ea668 0x2d265c 0x22dd 0x2205 0x1)* libc++abi.dylib: terminate called throwing an exception Thank you!

    Read the article

  • Can't figure out this file behavior in IOS 4.2

    - by Don Jones
    Odd behavior with file behavior. Here's the thing: I'm using the phone camera to snap a picture, and internally generating a thumbnail. I'm saving those as temp files in the Documents directory. Here's the complete code: - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info { UIImage *photo = [info objectForKey:@"UIImagePickerControllerOriginalImage"]; photo = [self scaleAndRotateImage:photo]; // save photo NSString *docsDir = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"]; NSLog(@"Writing to %@",docsDir); // save photo file NSLog(@"Saving photo as %@",[NSString stringWithFormat:@"%@/temp_photo.png",docsDir]); [UIImagePNGRepresentation(photo) writeToFile:[NSString stringWithFormat:@"%@/temp_photo.png",docsDir] atomically:YES]; // make and save thumbnail NSLog(@"Saving thumbnail as %@",[NSString stringWithFormat:@"%@/temp_thumb.png",docsDir]); UIImage *thumb = [self makeThumbnail:photo]; [UIImagePNGRepresentation(thumb) writeToFile:[NSString stringWithFormat:@"%@/temp_thumb.png",docsDir] atomically:YES]; NSFileManager *manager = [NSFileManager defaultManager]; NSError *error; NSArray *files = [manager contentsOfDirectoryAtPath:docsDir error:&error]; NSLog(@"\n\nThere are %d files in the documents directory %@",(files.count),docsDir); for (int i = 0; i < files.count; i++) { NSString *filename = [files objectAtIndex:i]; NSLog(@"Seeing filename %@",filename); } // done //[photo release]; //[thumb release]; [self dismissModalViewControllerAnimated:NO]; [delegate textInputFinished]; } As you can see, I've put quite a bit of logging in here in an attempt to figure out my problem (which is coming up). The log output to this point is: Writing to /var/mobile/Applications/77D792DC-A224-4A47-8A4C-BB7C557626F3/Documents Saving photo as /var/mobile/Applications/77D792DC-A224-4A47-8A4C-BB7C557626F3/Documents/temp_photo.png Saving thumbnail as /var/mobile/Applications/77D792DC-A224-4A47-8A4C-BB7C557626F3/Documents/temp_thumb.png There are 3 files in the documents directory /var/mobile/Applications/77D792DC-A224-4A47-8A4C-BB7C557626F3/Documents Seeing filename temp_photo.png Seeing filename temp_text.txt Seeing filename temp_thumb.png This is absolutely as-expected. I clearly have three files on the device. Here's the very next code that operates - the code that received the textInputFinished message: - (void)textInputFinished { NSFileManager *fileManager = [NSFileManager defaultManager]; NSString *docsDir = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"]; NSError *error; // get next filename NSString *filename; int i = 0; do { i++; filename = [NSString stringWithFormat:@"%@/reminder_%d",docsDir,i]; NSLog(@"Trying filename %@",filename); } while ([fileManager fileExistsAtPath:[filename stringByAppendingString:@".txt"]]); NSLog(@"New base filename is %@",filename); NSArray *files = [fileManager contentsOfDirectoryAtPath:docsDir error:&error]; NSLog(@"There are %d files in the directory %@",(files.count),docsDir); This is testing to get a new, non-temp, not-in-use filename. It does that - but then it says there aren't any files in the documents folder! Here's the logged output: Trying filename /var/mobile/Applications/77D792DC-A224-4A47-8A4C-BB7C557626F3/Documents/reminder_1 New base filename is /var/mobile/Applications/77D792DC-A224-4A47-8A4C-BB7C557626F3/Documents/reminder_1 There are 0 files in the directory /var/mobile/Applications/77D792DC-A224-4A47-8A4C-BB7C557626F3/Documents What the heck? Where did the three files go?

    Read the article

  • Find out when all processes in (void) is done?

    - by Emil
    Hey. I need to know how you can find out when all processes (loaded) from a - (void) are done, if it's possible. Why? I'm loading in data for a UITableView, and I need to know when a Loading... view can be replaced with the UITableView, and when I can start creating the cells. This is my code: - (void) reloadData { NSAutoreleasePool *releasePool = [[NSAutoreleasePool alloc] init]; NSLog(@"Reloading data."); NSURL *urlPosts = [NSURL URLWithString:[NSString stringWithFormat:@"%@", URL]]; NSError *lookupError = nil; NSString *data = [[NSString alloc] initWithContentsOfURL:urlPosts encoding:NSUTF8StringEncoding error:&lookupError]; postsData = [data componentsSeparatedByString:@"~"]; [data release], data = nil; urlPosts = nil; self.numberOfPosts = [[postsData objectAtIndex:0] intValue]; self.postsArrayID = [[postsData objectAtIndex:1] componentsSeparatedByString:@"#"]; self.postsArrayDate = [[postsData objectAtIndex:2] componentsSeparatedByString:@"#"]; self.postsArrayTitle = [[postsData objectAtIndex:3] componentsSeparatedByString:@"#"]; self.postsArrayComments = [[postsData objectAtIndex:4] componentsSeparatedByString:@"#"]; self.postsArrayImgSrc = [[postsData objectAtIndex:5] componentsSeparatedByString:@"#"]; NSMutableArray *writeToPlist = [NSMutableArray array]; NSMutableArray *writeToNoImagePlist = [NSMutableArray array]; NSMutableArray *imagesStored = [NSMutableArray arrayWithContentsOfFile:[rootPath stringByAppendingPathComponent:@"imagesStored.plist"]]; int loop = 0; for (NSString *postID in postsArrayID) { if ([imagesStored containsObject:[NSString stringWithFormat:@"%@.png", postID]]){ NSLog(@"Allready stored, jump to next. ID: %@", postID); continue; } NSLog(@"%@.png", postID); NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:[postsArrayImgSrc objectAtIndex:loop]]]; // If image contains anything, set cellImage to image. If image is empty, try one more time or use noImage.png, set in IB if (imageData == nil){ NSLog(@"imageData is empty before trying .jpeg"); // If image == nil, try to replace .jpg with .jpeg, and if that worked, set cellImage to that image. If that is also nil, use noImage.png, set in IB. imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:[[postsArrayImgSrc objectAtIndex:loop] stringByReplacingOccurrencesOfString:@".jpg" withString:@".jpeg"]]]; } if (imageData != nil){ NSLog(@"imageData is NOT empty when creating file"); [fileManager createFileAtPath:[rootPath stringByAppendingPathComponent:[NSString stringWithFormat:@"images/%@.png", postID]] contents:imageData attributes:nil]; [writeToPlist addObject:[NSString stringWithFormat:@"%@.png", postID]]; } else { [writeToNoImagePlist addObject:[NSString stringWithFormat:@"%@", postID]]; } imageData = nil; loop++; NSLog(@"imagePlist: %@\nnoImagePlist: %@", writeToPlist, writeToNoImagePlist); } NSMutableArray *writeToAllPlist = [NSMutableArray arrayWithArray:writeToPlist]; [writeToPlist addObjectsFromArray:[NSArray arrayWithContentsOfFile:nowPlist]]; [writeToAllPlist addObjectsFromArray:[NSArray arrayWithContentsOfFile:[rootPath stringByAppendingPathComponent:@"imagesStored.plist"]]]; [writeToNoImagePlist addObjectsFromArray:[NSArray arrayWithContentsOfFile:[rootPath stringByAppendingPathComponent:@"noImage.plist"]]]; [writeToPlist writeToFile:nowPlist atomically:YES]; [writeToAllPlist writeToFile:[rootPath stringByAppendingPathComponent:@"imagesStored.plist"] atomically:YES]; [writeToNoImagePlist writeToFile:[rootPath stringByAppendingPathComponent:@"noImage.plist"] atomically:YES]; [releasePool release]; }

    Read the article

  • iphone twitter posting

    - by user313100
    I have some twitter code I modified from: http://amanpages.com/sample-iphone-example-project/twitteragent-tutorial-tweet-from-iphone-app-in-one-line-code-with-auto-tinyurl/ His code used view alerts to login and post to twitter but I wanted to change mine to use windows. It is mostly working and I can login and post to Twitter. However, when I try to post a second time, the program crashes with a: Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '* -[NSCFString text]: unrecognized selector sent to instance 0xc2d560' I'm a bit of a coding newbie so any help would be appreciated. If I need to post more code, ask. #import "TwitterController.h" #import "xmacros.h" #define XAGENTS_TWITTER_CONFIG_FILE DOC_PATH(@"xagents_twitter_conifg_file.plist") static TwitterController* agent; @implementation TwitterController BOOL isLoggedIn; @synthesize parentsv, sharedLink; -(id)init { self = [super init]; maxCharLength = 140; parentsv = nil; isLogged = NO; isLoggedIn = NO; txtMessage = [[UITextView alloc] initWithFrame:CGRectMake(30, 225, 250, 60)]; UIImageView* bg = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"fb_message_bg.png"]]; bg.frame = txtMessage.frame; lblCharLeft = [[UILabel alloc] initWithFrame:CGRectMake(15, 142, 250, 20)]; lblCharLeft.font = [UIFont systemFontOfSize:10.0f]; lblCharLeft.textAlignment = UITextAlignmentRight; lblCharLeft.textColor = [UIColor whiteColor]; lblCharLeft.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0]; txtUsername = [[UITextField alloc]initWithFrame:CGRectMake(125, 190, 150, 30)]; txtPassword = [[UITextField alloc]initWithFrame:CGRectMake(125, 225, 150, 30)]; txtPassword.secureTextEntry = YES; lblId = [[UILabel alloc]initWithFrame:CGRectMake(15, 190, 100, 30)]; lblPassword = [[UILabel alloc]initWithFrame:CGRectMake(15, 225, 100, 30)]; lblTitle = [[UILabel alloc]initWithFrame:CGRectMake(80, 170, 190, 30)]; lblId.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0]; lblPassword.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0]; lblTitle.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0]; lblId.textColor = [UIColor whiteColor]; lblPassword.textColor = [UIColor whiteColor]; lblTitle.textColor = [UIColor whiteColor]; txtMessage.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0]; lblId.text = @"Username:"; lblPassword.text =@"Password:"; lblTitle.text = @"Tweet This Message"; lblId.textAlignment = UITextAlignmentRight; lblPassword.textAlignment = UITextAlignmentRight; lblTitle.textAlignment = UITextAlignmentCenter; txtUsername.borderStyle = UITextBorderStyleRoundedRect; txtPassword.borderStyle = UITextBorderStyleRoundedRect; txtMessage.delegate = self; txtUsername.delegate = self; txtPassword.delegate = self; login = [[UIButton alloc] init]; login = [UIButton buttonWithType:UIButtonTypeRoundedRect]; login.frame = CGRectMake(165, 300, 100, 30); [login setTitle:@"Login" forState:UIControlStateNormal]; [login addTarget:self action:@selector(onLogin) forControlEvents:UIControlEventTouchUpInside]; cancel = [[UIButton alloc] init]; cancel = [UIButton buttonWithType:UIButtonTypeRoundedRect]; cancel.frame = CGRectMake(45, 300, 100, 30); [cancel setTitle:@"Back" forState:UIControlStateNormal]; [cancel addTarget:self action:@selector(onCancel) forControlEvents:UIControlEventTouchUpInside]; post = [[UIButton alloc] init]; post = [UIButton buttonWithType:UIButtonTypeRoundedRect]; post.frame = CGRectMake(165, 300, 100, 30); [post setTitle:@"Post" forState:UIControlStateNormal]; [post addTarget:self action:@selector(onPost) forControlEvents:UIControlEventTouchUpInside]; back = [[UIButton alloc] init]; back = [UIButton buttonWithType:UIButtonTypeRoundedRect]; back.frame = CGRectMake(45, 300, 100, 30); [back setTitle:@"Back" forState:UIControlStateNormal]; [back addTarget:self action:@selector(onCancel) forControlEvents:UIControlEventTouchUpInside]; loading1 = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray]; loading1.frame = CGRectMake(140, 375, 40, 40); loading1.hidesWhenStopped = YES; [loading1 stopAnimating]; loading2 = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray]; loading2.frame = CGRectMake(140, 375, 40, 40); loading2.hidesWhenStopped = YES; [loading2 stopAnimating]; twitterWindow = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; [twitterWindow addSubview:txtUsername]; [twitterWindow addSubview:txtPassword]; [twitterWindow addSubview:lblId]; [twitterWindow addSubview:lblPassword]; [twitterWindow addSubview:login]; [twitterWindow addSubview:cancel]; [twitterWindow addSubview:loading1]; UIImageView* logo = [[UIImageView alloc] initWithFrame:CGRectMake(35, 165, 48, 48)]; logo.image = [UIImage imageNamed:@"Twitter_logo.png"]; [twitterWindow addSubview:logo]; [logo release]; twitterWindow2 = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; [twitterWindow2 addSubview:lblTitle]; [twitterWindow2 addSubview:lblCharLeft]; [twitterWindow2 addSubview:bg]; [twitterWindow2 addSubview:txtMessage]; [twitterWindow2 addSubview:lblURL]; [twitterWindow2 addSubview:post]; [twitterWindow2 addSubview:back]; [twitterWindow2 addSubview:loading2]; [twitterWindow2 bringSubviewToFront:txtMessage]; UIImageView* logo1 = [[UIImageView alloc] initWithFrame:CGRectMake(35, 155, 42, 42)]; logo1.image = [UIImage imageNamed:@"twitter-logo-twit.png"]; [twitterWindow2 addSubview:logo1]; [logo1 release]; twitterWindow.hidden = YES; twitterWindow2.hidden = YES; return self; } -(void) onStart { [[UIApplication sharedApplication]setStatusBarOrientation:UIInterfaceOrientationPortrait]; twitterWindow.hidden = NO; [twitterWindow makeKeyWindow]; [self refresh]; if(isLogged) { twitterWindow.hidden = YES; twitterWindow2.hidden = NO; [twitterWindow2 makeKeyWindow]; } } - (void)textFieldDidBeginEditing:(UITextField *)textField { [textField becomeFirstResponder]; } - (BOOL)textFieldShouldReturn:(UITextField *)textField { [textField resignFirstResponder]; return NO; } - (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{ const char* str = [text UTF8String]; int s = str[0]; if(s!=0) if((range.location + range.length) > maxCharLength){ return NO; }else{ int left = 139 - ([sharedLink length] + [textView.text length]); lblCharLeft.text= [NSString stringWithFormat:@"%d",left]; // this fix was done by Jackie //http://amanpages.com/sample-iphone-example-project/twitteragent-tutorial-tweet-from-iphone-app-in-one-line-code-with-auto-tinyurl/#comment-38026299 if([text isEqualToString:@"\n"]){ [textView resignFirstResponder]; return FALSE; }else{ return YES; } } int left = 139 - ([sharedLink length] + [textView.text length]); lblCharLeft.text= [NSString stringWithFormat:@"%d",left]; return YES; } -(void) onLogin { [loading1 startAnimating]; NSString *postURL = @"http://twitter.com/statuses/update.xml"; NSString *myRequestString = [NSString stringWithFormat:@""]; NSData *myRequestData = [ NSData dataWithBytes: [ myRequestString UTF8String ] length: [ myRequestString length ] ]; NSMutableURLRequest *request = [ [ NSMutableURLRequest alloc ] initWithURL: [ NSURL URLWithString:postURL ] ]; [ request setHTTPMethod: @"POST" ]; [ request setHTTPBody: myRequestData ]; NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:request delegate:self]; if (!theConnection) { UIAlertView* aler = [[UIAlertView alloc] initWithTitle:@"Network Error" message:@"Failed to Connect to twitter" delegate:nil cancelButtonTitle:@"Close" otherButtonTitles:nil]; [aler show]; [aler release]; } [request release]; } -(void) onCancel { [[NSUserDefaults standardUserDefaults] setValue:@"NotActive" forKey:@"Twitter"]; twitterWindow.hidden = YES; [[UIApplication sharedApplication]setStatusBarOrientation:UIInterfaceOrientationLandscapeRight]; } -(void) onPost { [loading2 startAnimating]; NSString *postURL = @"http://twitter.com/statuses/update.xml"; NSString *myRequestString; if(sharedLink){ myRequestString = [NSString stringWithFormat:@"&status=%@",[NSString stringWithFormat:@"%@\n%@",txtMessage.text,sharedLink]]; }else{ myRequestString = [NSString stringWithFormat:@"&status=%@",[NSString stringWithFormat:@"%@",txtMessage.text]]; } NSData *myRequestData = [ NSData dataWithBytes: [ myRequestString UTF8String ] length: [ myRequestString length ] ]; NSMutableURLRequest *request = [ [ NSMutableURLRequest alloc ] initWithURL: [ NSURL URLWithString:postURL ] ]; [ request setHTTPMethod: @"POST" ]; [ request setHTTPBody: myRequestData ]; NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:request delegate:self]; if (!theConnection) { UIAlertView* aler = [[UIAlertView alloc] initWithTitle:@"Network Error" message:@"Failed to Connect to twitter" delegate:nil cancelButtonTitle:@"Close" otherButtonTitles:nil]; [aler show]; [aler release]; } [request release]; } - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { // release the connection, and the data object [connection release]; if(isAuthFailed){ UIAlertView* aler = [[UIAlertView alloc] initWithTitle:@"Login Failed" message:@"Invalid ID/Password" delegate:nil cancelButtonTitle:@"Close" otherButtonTitles:nil]; [aler show]; [aler release]; }else{ UIAlertView* aler = [[UIAlertView alloc] initWithTitle:@"Connection Failed" message:@"Failed to connect to Twitter" delegate:nil cancelButtonTitle:@"Close" otherButtonTitles:nil]; [aler show]; [aler release]; } isAuthFailed = NO; } - (void)connectionDidFinishLoading:(NSURLConnection *)connection { isAuthFailed = NO; [loading1 stopAnimating]; [loading2 stopAnimating]; if(isLogged) { UIAlertView* aler = [[UIAlertView alloc] initWithTitle:@"Twitter" message:@"Tweet Posted!" delegate:nil cancelButtonTitle:@"Close" otherButtonTitles:nil]; [aler show]; [aler release]; txtMessage = @""; [self refresh]; } else { twitterWindow.hidden = YES; twitterWindow2.hidden = NO; [[NSNotificationCenter defaultCenter] postNotificationName:@"notifyTwitterLoggedIn" object:nil userInfo:nil]; } isLogged = YES; isLoggedIn = YES; } -(void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge { NSDictionary* config = [NSDictionary dictionaryWithObjectsAndKeys:txtUsername.text,@"username",txtPassword.text,@"password",nil]; [config writeToFile:XAGENTS_TWITTER_CONFIG_FILE atomically:YES]; if ([challenge previousFailureCount] == 0) { NSURLCredential *newCredential; newCredential=[NSURLCredential credentialWithUser:txtUsername.text password:txtPassword.text persistence:NSURLCredentialPersistenceNone]; [[challenge sender] useCredential:newCredential forAuthenticationChallenge:challenge]; } else { isAuthFailed = YES; [[challenge sender] cancelAuthenticationChallenge:challenge]; } } -(void) refresh { NSDictionary* config = [NSDictionary dictionaryWithContentsOfFile:XAGENTS_TWITTER_CONFIG_FILE]; if(config){ NSString* uname = [config valueForKey:@"username"]; if(uname){ txtUsername.text = uname; } NSString* pw = [config valueForKey:@"password"]; if(pw){ txtPassword.text = pw; } } } + (TwitterController*)defaultAgent{ if(!agent){ agent = [TwitterController new]; } return agent; } -(void)dealloc { [super dealloc]; [txtMessage release]; [txtUsername release]; [txtPassword release]; [lblId release]; [lblPassword release]; [lblURL release]; [twitterWindow2 release]; [twitterWindow release]; } @end

    Read the article

  • Received memory warning. Level=2, Program received signal: “0”.

    - by sabby
    Hi friends I am getting images from webservice and loading these images in table view.But when i continue to scroll the program receives memory warning level1,level2 and then app exits with status 0.That happens only in device not in simulator. Here is my code which i am putting please help me out. - (void)viewDidLoad { [super viewDidLoad]; UIButton *infoButton = [[UIButton alloc] initWithFrame:CGRectMake(0, -4, 62, 30)]; [infoButton setBackgroundImage:[UIImage imageNamed: @"back.png"] forState:UIControlStateNormal]; [infoButton addTarget:self action:@selector(backButtonClicked) forControlEvents:UIControlEventTouchUpInside]; UIBarButtonItem *customBarButtomItem = [[UIBarButtonItem alloc] initWithCustomView:infoButton]; self.navigationItem.leftBarButtonItem = customBarButtomItem; [customBarButtomItem release]; [infoButton release]; UIButton *homeButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 62, 30)]; [homeButton setBackgroundImage:[UIImage imageNamed: @"home.png"] forState:UIControlStateNormal]; [homeButton.titleLabel setFont:[UIFont systemFontOfSize:11]]; //[homeButton setTitle:@"UPLOAD" forState:UIControlStateNormal]; [homeButton addTarget:self action:@selector(homeButtonClicked) forControlEvents:UIControlEventTouchUpInside]; UIBarButtonItem *rightBarButtom = [[UIBarButtonItem alloc] initWithCustomView:homeButton]; self.navigationItem.rightBarButtonItem = rightBarButtom; [rightBarButtom release]; [homeButton release]; sellerTableView=[[UITableView alloc]initWithFrame:CGRectMake(0, 0, 320, 416) style:UITableViewStylePlain]; sellerTableView.delegate=self; sellerTableView.dataSource=self; sellerTableView.backgroundColor=[UIColor clearColor]; sellerTableView.scrollEnabled=YES; //table.separatorColor=[UIColor grayColor]; //table.separatorColor=[UIColor whiteColor]; //[[table layer]setRoundingMode:NSNumberFormatterRoundDown]; [[sellerTableView layer]setBorderColor:[[UIColor darkGrayColor]CGColor]]; [[sellerTableView layer]setBorderWidth:2]; //[[productTable layer]setCornerRadius:10.3F]; [self.view addSubview:sellerTableView]; appDel = (SnapItAppAppDelegate*)[[UIApplication sharedApplication] delegate]; } -(void)viewWillAppear:(BOOL)animated { spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray]; spinner.center = self.view.center; [self.view addSubview:spinner]; [spinner startAnimating]; [[SnapItParsing sharedInstance]assignSender:self]; [[SnapItParsing sharedInstance]startParsingForShowProducts:appDel.userIdString]; [sellerTableView reloadData]; } -(void)showProducts:(NSMutableArray*)proArray { if (spinner) { [spinner stopAnimating]; [spinner removeFromSuperview]; [spinner release]; spinner = nil; } if ([[[proArray objectAtIndex:1]objectForKey:@"Success"]isEqualToString:@"True"]) { //[self.navigationController popViewControllerAnimated:YES]; //self.view.alpha=.12; if (productInfoArray) { [productInfoArray release]; } productInfoArray=[[NSMutableArray alloc]init]; for (int i=2; i<[proArray count]; i++) { NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; [productInfoArray addObject:[proArray objectAtIndex:i]]; NSLog(@"data fetch array is====> /n%@",productInfoArray); [pool release]; } } } #pragma mark (tableview methods) - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{ return 100; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { //return [resultarray count]; return [productInfoArray count]; } -(void)loadImagesInBackground:(NSNumber *)index{ NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; NSMutableDictionary *frame = [[productInfoArray objectAtIndex:[index intValue]] retain]; //NSLog(@"frame value ==>%@",[[frame objectForKey:@"Image"]length]); NSString *frameImagePath = [NSString stringWithFormat:@"http://apple.com/snapit/products/%@",[frame objectForKey:@"Image"]]; NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:frameImagePath]]; NSLog(@"FRAME IMAGE%d",[[frame valueForKey:@"Image" ]length]); if([[frame valueForKey:@"Image"] length] == 0){ NSString *imagePath = [[NSString alloc] initWithFormat:@"%@/%@",[[NSBundle mainBundle] resourcePath],@"no_image.png"]; UIImage *image = [UIImage imageWithContentsOfFile:imagePath]; [frame setObject:image forKey:@"friendImage"]; [imagePath release]; //[image release]; } else { //NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:frameImagePath]]; NSLog(@"image data length ==>%d",[imageData length]); if([imageData length] == 0){ NSString *imagePath = [[NSString alloc] initWithFormat:@"%@/%@",[[NSBundle mainBundle] resourcePath],@"no_image.png"]; UIImage *image = [UIImage imageWithContentsOfFile:imagePath]; [frame setObject:image forKey:@"friendImage"]; [imagePath release]; //[image release]; } else { //UIImage *image = [[UIImage alloc] initWithData:imageData]; UIImage *image = [UIImage imageWithData:imageData]; [frame setObject:image forKey:@"friendImage"]; //[image release]; } } [frame release]; frame = nil; [self performSelectorOnMainThread:@selector(reloadTable:) withObject:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:[index intValue] inSection:0]] waitUntilDone:NO]; [pool release]; } -(void)reloadTable:(NSArray *)array{ NSLog(@"array ==>%@",array); [sellerTableView reloadRowsAtIndexPaths:array withRowAnimation:UITableViewRowAnimationNone]; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *celltype=@"cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:celltype]; for (UIView *view in cell.contentView.subviews) { [view removeFromSuperview]; } if (cell == nil) { cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"] autorelease]; cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; cell.backgroundColor=[UIColor clearColor]; //cell.textLabel.text=[[resultarray objectAtIndex:indexPath.row] valueForKey:@"Service"]; /*UIImage *indicatorImage = [UIImage imageNamed:@"indicator.png"]; cell.accessoryView = [[[UIImageView alloc] initWithImage:indicatorImage] autorelease];*/ /*NSThread *thread=[[NSThread alloc]initWithTarget:self selector:@selector() object:nil]; [thread setStackSize:44]; [thread start];*/ cell.backgroundView=[[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"cell.png"]]autorelease]; // [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"back.png"]] autorelease]; cell.selectionStyle=UITableViewCellSelectionStyleNone; } UIImageView *imageView= [[UIImageView alloc] initWithFrame:CGRectMake(19, 15, 75, 68)]; imageView.contentMode = UIViewContentModeScaleToFill; // @synchronized(self) //{ NSMutableDictionary *dict = [productInfoArray objectAtIndex:indexPath.row]; if([dict objectForKey:@"friendImage"] == nil){ imageView.backgroundColor = [UIColor clearColor]; if ([dict objectForKey:@"isThreadLaunched"] == nil) { [NSThread detachNewThreadSelector:@selector(loadImagesInBackground:) toTarget:self withObject:[NSNumber numberWithInt:indexPath.row]]; [dict setObject:@"Yes" forKey:@"isThreadLaunched"]; } }else { imageView.image =[dict objectForKey:@"friendImage"]; } //NSString *imagePath = [[NSString alloc] initWithFormat:@"%@/%@",[[NSBundle mainBundle] resourcePath],@"no_image.png"]; //imageView.layer.cornerRadius = 20.0;//vk //imageView.image=[UIImage imageWithContentsOfFile:imagePath]; //imageView.layer.masksToBounds = YES; //imageView.layer.borderColor = [UIColor darkGrayColor].CGColor; //imageView.layer.borderWidth = 1.0;//vk //imageView.layer.cornerRadius=7.2f; [cell.contentView addSubview:imageView]; //[imagePath release]; [imageView release]; imageView = nil; //} UILabel *productCodeLabel = [[UILabel alloc] initWithFrame:CGRectMake(105, 7, 60,20 )]; productCodeLabel.textColor = [UIColor whiteColor]; productCodeLabel.backgroundColor=[UIColor clearColor]; productCodeLabel.text=[NSString stringWithFormat:@"%@",@"Code"]; [cell.contentView addSubview:productCodeLabel]; [productCodeLabel release]; UILabel *CodeValueLabel = [[UILabel alloc] initWithFrame:CGRectMake(170, 7, 140,20 )]; CodeValueLabel.textColor = [UIColor whiteColor]; CodeValueLabel.backgroundColor=[UIColor clearColor]; CodeValueLabel.text=[NSString stringWithFormat:@"%@",[[productInfoArray objectAtIndex:indexPath.row]valueForKey:@"ID"]]; [cell.contentView addSubview:CodeValueLabel]; [CodeValueLabel release]; UILabel *productNameLabel = [[UILabel alloc] initWithFrame:CGRectMake(105, 35, 60,20 )]; productNameLabel.textColor = [UIColor whiteColor]; productNameLabel.backgroundColor=[UIColor clearColor]; productNameLabel.text=[NSString stringWithFormat:@"%@",@"Name"]; [cell.contentView addSubview:productNameLabel]; [productNameLabel release]; UILabel *NameValueLabel = [[UILabel alloc] initWithFrame:CGRectMake(170, 35, 140,20 )]; NameValueLabel.textColor = [UIColor whiteColor]; NameValueLabel.backgroundColor=[UIColor clearColor]; NameValueLabel.text=[NSString stringWithFormat:@"%@",[[productInfoArray objectAtIndex:indexPath.row]valueForKey:@"Title"]]; [cell.contentView addSubview:NameValueLabel]; [NameValueLabel release]; UILabel *dateLabel = [[UILabel alloc] initWithFrame:CGRectMake(105, 68, 60,20 )]; dateLabel.textColor = [UIColor whiteColor]; dateLabel.backgroundColor=[UIColor clearColor]; dateLabel.text=[NSString stringWithFormat:@"%@",@"Date"]; [cell.contentView addSubview:dateLabel]; [dateLabel release]; UILabel *dateValueLabel = [[UILabel alloc] initWithFrame:CGRectMake(170, 68, 140,20 )]; dateValueLabel.textColor = [UIColor whiteColor]; dateValueLabel.backgroundColor=[UIColor clearColor]; dateValueLabel.text=[NSString stringWithFormat:@"%@",[[productInfoArray objectAtIndex:indexPath.row]valueForKey:@"PostedDate"]]; dateValueLabel.font=[UIFont systemFontOfSize:14]; dateValueLabel.numberOfLines=3; dateValueLabel.adjustsFontSizeToFitWidth=YES; [dateValueLabel setLineBreakMode:UILineBreakModeCharacterWrap]; [cell.contentView addSubview:dateValueLabel]; [dateValueLabel release]; } Please-2 help me out ,where i am doing mistake.....

    Read the article

  • Terminating app due to uncaught exception 'NSGenericException', reason: '*** Collection <CALayerArray: 0x66522e0> was mutated while being enumerated

    - by fahu
    some times my app crashed by showing * Collection was mutated while being enumerated . This is occurring in same line of code all the time.please help me on this issue. i stuck on this. the app is crashing at pushing view controller line of my code.but it is not frequent one. my error console Terminating app due to uncaught exception 'NSGenericException', reason: '* Collection CALayerArray: 0x1030c730 was mutated while being enumerated. "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "" )' my code: - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { ServiceDetails *service=[[ServiceDetails alloc] initWithNibName:@"ServiceDetails" bundle:nil]; CompanyListingForm *list=[[CompanyListingForm alloc]initWithNibName:@"CompanyListingForm" bundle:nil]; [category_company_text resignFirstResponder]; if(viewHoldingTable) { [viewHoldingTable removeFromSuperview]; } if (category_clicked_flag==0) { if (location_or_cat_com==0) { NSMutableArray *get=[district_array objectAtIndex:indexPath.row]; locationid=[[get objectAtIndex:0]intValue]; [location_textfield resignFirstResponder]; location_textfield.text=[get objectAtIndex:1]; } else { if (draggingView) { [draggingView removeFromSuperview]; } if (viewHoldingTable) { [viewHoldingTable removeFromSuperview]; } NSMutableArray *get=[company_array objectAtIndex:indexPath.row]; category_company_text.text=[get objectAtIndex:1]; service.ida=[NSString stringWithFormat:@"%d",[[get objectAtIndex:0] intValue]]; service.idloc=[NSString stringWithFormat:@"%d",locationid]; [self.navigationController pushViewController:service animated:YES];//getting error at this point. //[emer release]; } } else { if (location_or_cat_com==0) { NSMutableArray *get=[district_array objectAtIndex:indexPath.row]; locationid=[[get objectAtIndex:0]intValue]; [location_textfield resignFirstResponder]; location_textfield.text=[get objectAtIndex:1]; } else { NSMutableArray *get=[category_array objectAtIndex:indexPath.row]; category_company_text.text=[get objectAtIndex:1]; int catid=[[get objectAtIndex:0]intValue]; list.IDForLoc=[NSString stringWithFormat:@"%d",locationid]; list.IDForCat=[NSString stringWithFormat:@"%d",catid]; list.companydetails=[get objectAtIndex:1]; [self.navigationController pushViewController:list animated:YES];//getting error at this point. } } [service release]; [list release]; }

    Read the article

  • UITableView's NSString memory leak on iphone when encoding with NSUTF8StringEncoding

    - by vince
    my UITableView have serious memory leak problem only when the NSString is NOT encoding with NSASCIIStringEncoding. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"cell"; UILabel *textLabel1; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease]; textLabel1 = [[UILabel alloc] initWithFrame:CGRectMake(105, 6, 192, 22)]; textLabel1.tag = 1; textLabel1.textColor = [UIColor whiteColor]; textLabel1.backgroundColor = [UIColor blackColor]; textLabel1.numberOfLines = 1; textLabel1.adjustsFontSizeToFitWidth = NO; [textLabel1 setFont:[UIFont boldSystemFontOfSize:19]]; [cell.contentView addSubview:textLabel1]; [textLabel1 release]; } else { textLabel1 = (UILabel *)[cell.contentView viewWithTag:1]; } NSDictionary *tmpDict = [listOfInfo objectForKey:[NSString stringWithFormat:@"%@",indexPath.row]]; textLabel1.text = [tmpDict objectForKey:@"name"]; return cell; } -(void) readDatabase { NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDir = [documentPaths objectAtIndex:0]; databasePath = [documentsDir stringByAppendingPathComponent:[NSString stringWithFormat:@"%@",myDB]]; sqlite3 *database; if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) { const char sqlStatement = [[NSString stringWithFormat:@"select id,name from %@ order by orderid",myTable] UTF8String]; sqlite3_stmt *compiledStatement; if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) { while(sqlite3_step(compiledStatement) == SQLITE_ROW) { NSString *tmpid = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 0)]; NSString *tmpname = [NSString stringWithCString:(const char *)sqlite3_column_text(compiledStatement, 1) encoding:NSUTF8StringEncoding]; [listOfInfo setObject:[[NSMutableDictionary alloc] init] forKey:tmpid]; [[listOfInfo objectForKey:tmpid] setObject:[NSString stringWithFormat:@"%@", tmpname] forKey:@"name"]; } } sqlite3_finalize(compiledStatement); debugNSLog(@"sqlite closing"); } sqlite3_close(database); } when i change the line NSString *tmpname = [NSString stringWithCString:(const char *)sqlite3_column_text(compiledStatement, 1) encoding:NSUTF8StringEncoding]; to NSString *tmpname = [NSString stringWithCString:(const char *)sqlite3_column_text(compiledStatement, 1) encoding:NSASCIIStringEncoding]; the memory leak is gone i tried NSString stringWithUTF8String and it still leak. i've also tried: NSData *dtmpname = [NSData dataWithBytes:sqlite3_column_blob(compiledStatement, 1) length:sqlite3_column_bytes(compiledStatement, 1)]; NSString *tmpname = [[[NSString alloc] initWithData:dtmpname encoding:NSUTF8StringEncoding] autorelease]; and the problem remains, the leak occur when u start scrolling the tableview. i've actually tried other encoding and it seems that only NSASCIIStringEncoding works(no memory leak) any idea how to get rid of this problem?

    Read the article

  • How do I upload an NSImage(NSData)to Twitpic with OAMutableURLRequest?

    - by timothy5216
    I'm using OAConsumer in my xAuth twitterEngine and i'm adding Twitpic OAuth Echo to it. But it won't POST the NSData. here is some of my code: //other file NSArray *reps = [[imageToUpload image] representations]; NSData *imageData = [NSBitmapImageRep representationOfImageRepsInArray:reps usingType:NSJPEGFileType properties:nil]; [twitter testUploadImageData:imageData withMessage:@"Hello WORLD!!" toURL:[NSURL URLWithString:uploadURL.stringValue]]; // - (void)testUploadImageData:(NSData *)data withMessage:(NSString *)message toURL:(NSURL *)url; { //url = @"http://api.twitpic.com/2/upload.xml" //message = @"Hello WORLD!!" NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; NSString *String = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding]; NSLog(@"dataString: %@",String); OAMutableURLRequest *request = [[OAMutableURLRequest alloc] initWithURL:url consumer:self.consumer token:_accessToken realm:nil signatureProvider:nil]; // Setup POST body [request setHTTPMethod:@"POST"]; //NSString *stringBoundary = [NSString stringWithString:@"0xKhTmLbOuNdArY"]; //NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", stringBoundary]; // NSString *stringBoundarySeparator = [NSString stringWithFormat:@"\r\n--%@\r\n", stringBoundary]; /* NSMutableString *postString = [NSMutableString string]; [postString appendString:@"\r\n"]; [postString appendString:stringBoundarySeparator]; [postString appendString:[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"message\"\r\n\r\n%@", message]]; [postString appendString:stringBoundarySeparator]; [postString appendString:[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"media\"; filename=\"%@\"\r\n", @"file.jpg"]]; [postString appendString:@"Content-Type: image/jpg\r\n"]; [postString appendString:@"Content-Transfer-Encoding: binary\r\n\r\n"]; // Setting up the POST request's multipart/form-data body NSMutableData *postBody = [NSMutableData data]; [postBody appendData:[postString dataUsingEncoding:NSUTF8StringEncoding]]; [postBody appendData:data]; [request setHTTPBody:postBody]; */ [request setHTTPMethod:@"POST"]; NSString *thing = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding]; NSLog(@"%@",thing); [request setParameters:[NSArray arrayWithObjects: [OARequestParameter requestParameterWithName:@"oauth_token" value:_accessToken.key], [OARequestParameter requestParameterWithName:@"X-Auth-Service-Provider" value:@"https://api.twitter.com/1/account/verify_credentials.json"], [OARequestParameter requestParameterWithName:@"key" value:@"my-key-here :P"], [OARequestParameter requestParameterWithName:@"message" value:message], //iv'e changed this many times. I was just trying this to see if it works [OARequestParameter requestParameterWithName:@"media" value:thing], nil]]; OAAsynchronousDataFetcher *dataFetcher = [[OAAsynchronousDataFetcher alloc] init]; [dataFetcher initWithRequest:request delegate:self didFinishSelector:@selector(uploadDidUpload:withData:) didFailSelector:@selector(uploadDidFail:withData:)]; [dataFetcher start]; [dataFetcher release]; [request release]; [pool drain]; } I'm authenticated but it still won't POST the data :(

    Read the article

  • Problem with writeData

    - by zp26
    Hi, I have a problem with my code. I want to create a XML file like this: <name>myName<name> <x>myX<x> <y>myY<y> <z>myZ<z> but my file is: <name>myName<name><x>myX<x><y>myY<y><z>myZ<z> Can i have this text formatting? This is my code: -(void)salvataggioInXML:(NSString*)name:(float)x:(float)y:(float)z{ NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectoryPath = [paths objectAtIndex:0]; NSString *filePath = [documentsDirectoryPath stringByAppendingPathComponent:@"filePosizioni.xml"]; NSFileHandle *myHandle = [NSFileHandle fileHandleForUpdatingAtPath:filePath]; [myHandle seekToEndOfFile]; NSString *tagName = [NSString stringWithFormat:@"<name>%@<name>", name]; NSString *tagX = [NSString stringWithFormat:@"<x>%f<x>", name]; NSString *tagY = [NSString stringWithFormat:@"<y>%f<y>", name]; NSString *tagZ = [NSString stringWithFormat:@"<z>%f<z>", name]; NSData* dataName = [tagName dataUsingEncoding: NSASCIIStringEncoding]; NSData* dataX = [tagX dataUsingEncoding: NSASCIIStringEncoding]; NSData* dataY = [tagY dataUsingEncoding: NSASCIIStringEncoding]; NSData* dataZ = [tagZ dataUsingEncoding: NSASCIIStringEncoding]; [myHandle writeData:dataName]; NSLog(@"writeok"); [myHandle seekToEndOfFile]; [myHandle writeData:dataX]; NSLog(@"writeok"); [myHandle seekToEndOfFile]; [myHandle writeData:dataY]; NSLog(@"writeok"); [myHandle seekToEndOfFile]; [myHandle writeData:dataZ]; NSLog(@"writeok"); [myHandle seekToEndOfFile]; NSLog(@"zp26 %@",filePath); }

    Read the article

  • want to fetch the friends list of facebook thorough fbconnect in iphone using objective-c ?

    - by uttam
    how to fetch the friends list of facebook in iphone through fbconnect in objective-c? I am using this code (void)getUserName { NSString *fql = [NSString localizedStringWithFormat: @"SELECT uid FROM user WHERE is_app_user = 1 AND uid IN (SELECT uid2 FROM friend WHERE uid1 = %lld)",[FBSession session].uid]; NSDictionary* params = [NSDictionary dictionaryWithObject:fql forKey:@"query"]; [[FBRequest requestWithDelegate:self] call:@"facebook.friends.get" params:params]; } - (void)request:(FBRequest*)request didLoad:(id)result { if ([request.method isEqualToString:@"facebook.fql.query"]) { NSArray* users = result; NSDictionary* user = [users objectAtIndex:0]; NSString* name = [user objectForKey:@"name"]; _label.text = [NSString stringWithFormat:@"Logged in as %@", name]; } else if ([request.method isEqualToString:@"facebook.users.setStatus"]) { NSString* success = result; if ([success isEqualToString:@"1"]) { _label.text = [NSString stringWithFormat:@"Status successfully set"]; } else { _label.text = [NSString stringWithFormat:@"Problem setting status"]; } } else if ([request.method isEqualToString:@"facebook.freinds.get"]) { if(myList==nil) { NSArray* users = result; myList =[[NSArray alloc] initWithArray: users]; for(NSInteger i=0;i<[users count];i++) { NSDictionary* user = [users objectAtIndex:i]; NSString* uid = [user objectForKey:@"uid"]; NSString* fql = [NSString stringWithFormat: @"select name from user where uid == %@", uid]; NSDictionary* params = [NSDictionary dictionaryWithObject:fql forKey:@"query"]; [[FBRequest requestWithDelegate:self] call:@"facebook.fql.query" params:params]; } } else { NSArray* users = result; NSDictionary* user = [users objectAtIndex:0]; NSString* name = [user objectForKey:@"name"]; //txtView.text=[NSString localizedStringWithFormat:@"%@%@,\n",txtView.text,name]; NSLog(name); }} I want to get the friends list from facebook and then search/modify then add it to my addressbook. I know this code is doing this but I don't know how to use it or where do I use it.. If you could please post something or just elaborate on how do I use your code thru fbconnect framework. I have implemented upto get permissions and publish feeds one's wall. But please can you post here about the layout details of the results, like what do Ineed to use on the layout point of view.

    Read the article

  • iPhone Development: Use POST to submit a form

    - by Mario
    I've got the following html form: <form method="post" action="http://shk.ecomd.de/up.php" enctype="multipart/form-data"> <input type="hidden" name="id" value="12345" /> <input type="file" name="pic" /> <input type="submit" /> </form> And the following iPhone SDK Submit method: - (void)sendfile { UIImage *tempImage = [UIImage imageNamed:@"image.jpg"]; NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init]; [request setHTTPMethod:@"POST"]; [request setURL:[NSURL URLWithString:@"http://url..../form.php"]]; NSString *boundary = @"------------0xKhTmLbOuNdArY"; NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary]; [request addValue:contentType forHTTPHeaderField: @"Content-Type"]; NSMutableData *body = [NSMutableData data]; [body appendData:[[NSString stringWithFormat:@"\r\n%@\r\n",boundary] dataUsingEncoding:NSASCIIStringEncoding]]; [body appendData:[@"Content-Disposition: form-data; name=\"id\"\r\n\r\n" dataUsingEncoding:NSASCIIStringEncoding]]; [body appendData:[@"12345" dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[[NSString stringWithFormat:@"\r\n%@\r\n",boundary] dataUsingEncoding:NSASCIIStringEncoding]]; [body appendData:[@"Content-Disposition: form-data; name=\"pic\"; filename=\"photo.png\"\r\n" dataUsingEncoding:NSASCIIStringEncoding]]; [body appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSASCIIStringEncoding]]; [body appendData:[NSData dataWithData:UIImageJPEGRepresentation(tempImage, 90)]]; [body appendData:[[NSString stringWithFormat:@"\r\n%@",boundary] dataUsingEncoding:NSASCIIStringEncoding]]; // setting the body of the post to the reqeust [request setHTTPBody:body]; NSError *error; NSURLResponse *response; NSData* result = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]; NSString* aStr = [[[NSString alloc] initWithData:result encoding:NSASCIIStringEncoding] autorelease]; NSLog(@"Result: %@", aStr); [request release]; } This does not work, but I have no clue why. Can you please help me?!! What am I doing wrong?

    Read the article

  • How to create constant NSString by concatenating strings in Obj-C ?

    - by eric-morand
    Hi guys, I'm trying to instanciate a constant NSString by concatanating other NSString instances. Here is what I'm doing in my implementation file : static NSString *const MY_CONST = @"TEST"; static NSString *const MY_CONCATENATE_CONST = [NSString stringWithFormat:@"STRING %@", MY_CONST]; It leads to the following compilation error : Initializer element is not constant I suppose this is because stringWithFormat doesn't return a constant NSString, but since there is no other way to concatenate strings in Obj-C, what am I supposed to do ? Thanks for your help, Eric.

    Read the article

  • How do you delete rows from UITableView?

    - by James
    This has been bugging me for hours now and i have not been able to figure it out. I am importing data into a tableview using core data and NSMutableArray. As shown below. CORE DATA ARRAY NSMutableArray *mutableFetchResults = [CoreDataHelper getObjectsFromContext:@"Spot" :@"Name" :YES :managedObjectContext]; self.entityArray = mutableFetchResults; TABLE VIEW - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { NSManagedObject *object = (NSManagedObject *)[entityArray objectAtIndex:indexPath.row]; NSString *CellIdentifier = @"Cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease]; } NSString *lat1 = [object valueForKey:@"Email"]; //NSLog(@"Current Spot Latitude:%@",lat1); float lat2 = [lat1 floatValue]; //NSLog(@"Current Spot Latitude Float:%g", lat2); NSString *long1 = [object valueForKey:@"Description"]; //NSLog(@"Current Spot Longitude:%@",long1); float long2 = [long1 floatValue]; //NSLog(@"Current Spot Longitude Float:%g", long2); //Getting current location from NSDictionary CoreDataTestAppDelegate *appDelegate = (CoreDataTestAppDelegate *) [[UIApplication sharedApplication] delegate]; NSString *locLat = [NSString stringWithFormat:appDelegate.latitude]; float locLat2 = [locLat floatValue]; //NSLog(@"Lat: %g",locLat2); NSString *locLong = [NSString stringWithFormat:appDelegate.longitude]; float locLong2 = [locLong floatValue]; //NSLog(@"Long: %g",locLong2); //Distance Shizzle //Prime's Location CLLocation *loc1 = [[CLLocation alloc] initWithLatitude:lat2 longitude:long2]; //Home Location CLLocation *loc2 = [[CLLocation alloc] initWithLatitude:locLat2 longitude:locLong2]; double distance = [loc1 getDistanceFrom: loc2] / 1000; int myInt = (int)(distance + (distance>0 ? 0.5 : -0.5)); //NSLog(@"INT VAL :%i", myInt); NSMutableString* converted = [NSMutableString stringWithFormat:@"%.1f", distance]; [converted appendString: @" Km"]; //NSLog(@"Distance between Prime and home = %g", converted); if (myInt < 11) { cell.textLabel.text = [object valueForKey:@"Name"]; cell.detailTextLabel.text = [NSString stringWithFormat:converted]; } else { } // Configure the cell... return cell; } I am trying to get the table only to display results that are within a certain distance. This method here works apart from the fact that the results over a certain distance are still in the table, they are just not graphically visible. I am led to believe that i have to carry out the filtering process before the formatting the table but i can not seem to do this. Please help. My xcode skills are not brilliant so code suggestions would be helpfull.

    Read the article

  • Can't get rid of this warning?

    - by NextRev
    I'm getting this warning "Format not a string literal and no format arguments? Any ideas? -(BOOL)isFirstPointReached{ NSString *firstPoint = [NSString stringWithFormat:[pointsToFillArray objectAtIndex:0]]; NSString *lastPoint = [NSString stringWithFormat:[pointsToFillArray lastObject]]; if([firstPoint isEqualToString:lastPoint]){ return YES; } else{ return NO; } }

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >