Search Results

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

Page 10/25 | < Previous Page | 6 7 8 9 10 11 12 13 14 15 16 17  | Next Page >

  • Float Conversion Issue

    - by user1407570
    I have an issue after converted a float from a string, the result of my operation is null The NSLogs give the right value but vitesseMoyenne is equal to null -(void)setVitesseMoyenne:(float)uneDistanceTotale:(NSString*)unTempsTotal { //float tempEnFloat = [unTempsTotal floatValue]; NSLog(@"%@",unTempsTotal); float calculVitesseMoyenne = uneDistanceTotale / [unTempsTotal floatValue]; NSLog(@"%f",calculVitesseMoyenne); vitesseMoyenne = [NSString stringWithFormat:@"%f", calculVitesseMoyenne]; } Can you see what is wrong ?

    Read the article

  • Cell contents changing for rows present outside the height of tableview(to see this cells, we shud s

    - by wolverine
    I have set the size of the tableView that I show as the popoverController as 4*rowheight. And I am using 12cells in the tableView. Each cell contains an image and a label. I can see all the cells by scrolling. Upto 5th cell its ok. After th2 5th cell, the label and the image that I am using in the first four cells are being repeated for the remaining cells. And If I select the cell, the result is accurately shown. But when I again take the tableView, the image and labels are not accurate even for the first 5 cells. All are changed but the selection is giving the correct result. Can anyone help me?? - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [self tableviewCellWithReuseIdentifier:CellIdentifier rowNumber:indexPath.row]; } //tableView.backgroundColor = [UIColor clearColor]; return cell; } - (UITableViewCell *)tableviewCellWithReuseIdentifier:(NSString *)identifier rowNumber:(NSInteger)row { CGRect rect; rect = CGRectMake(0.0, 0.0, 360.0, ROW_HEIGHT); UITableViewCell *cell = [[[UITableViewCell alloc] initWithFrame:rect reuseIdentifier:identifier] autorelease]; UIImageView *myImageView = [[UIImageView alloc] initWithFrame:CGRectMake(10.00, 10.00, 150.00, 100.00)]; myImageView.tag = IMAGE_TAG; [cell.contentView addSubview:myImageView]; [myImageView release]; UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(170.00, -10.00, 170.00, 80.00)]; label.tag = LABEL_TAG; [label setBackgroundColor:[UIColor clearColor]]; [label setTextColor:[UIColor blackColor]]; [label setFont:[UIFont fontWithName:@"AmericanTypewriter" size:22]]; [label setTextAlignment:UITextAlignmentLeft]; [cell.contentView addSubview:label]; [label release]; if (row == 0) { UIImageView *imageView = (UIImageView *)[cell viewWithTag:IMAGE_TAG]; imageView.image = [UIImage imageNamed:[NSString stringWithFormat:@"cover_v.jpg"]]; UILabel *mylabel = (UILabel *)[cell viewWithTag:LABEL_TAG]; mylabel.text = [NSString stringWithFormat:@"COVER PAGE"]; } }

    Read the article

  • objective C convert NSString to unsigned

    - by user1501354
    I have changed my question. I want to convert an NSString to an unsigned int. Why? Because I want to do parallel payment in PayPal. Below I have given my coding in which I want to convert the NSString to an unsigned int. My query is: //optional, set shippingEnabled to TRUE if you want to display shipping //options to the user, default: TRUE [PayPal getPayPalInst].shippingEnabled = TRUE; //optional, set dynamicAmountUpdateEnabled to TRUE if you want to compute //shipping and tax based on the user's address choice, default: FALSE [PayPal getPayPalInst].dynamicAmountUpdateEnabled = TRUE; //optional, choose who pays the fee, default: FEEPAYER_EACHRECEIVER [PayPal getPayPalInst].feePayer = FEEPAYER_EACHRECEIVER; //for a payment with multiple recipients, use a PayPalAdvancedPayment object PayPalAdvancedPayment *payment = [[PayPalAdvancedPayment alloc] init]; payment.paymentCurrency = @"USD"; // A payment note applied to all recipients. payment.memo = @"A Note applied to all recipients"; //receiverPaymentDetails is a list of PPReceiverPaymentDetails objects payment.receiverPaymentDetails = [NSMutableArray array]; NSArray *emailArray = [NSArray arrayWithObjects:@"[email protected]",@"[email protected]", nil]; for (int i = 1; i <= 2; i++) { PayPalReceiverPaymentDetails *details = [[PayPalReceiverPaymentDetails alloc] init]; // Customize the payment notes for one of the three recipient. if (i == 2) { details.description = [NSString stringWithFormat:@"Component %d", i]; } details.recipient = [NSString stringWithFormat:@"%@",[emailArray objectAtIndex:i-1]]; unsigned order; if (i==1) { order = [[feeArray objectAtIndex:0] unsignedIntValue]; } if (i==2) { order = [[amountArray objectAtIndex:0] unsignedIntValue]; } //subtotal of all items for this recipient, without tax and shipping details.subTotal = [NSDecimalNumber decimalNumberWithMantissa:order exponent:-4 isNegative:FALSE]; //invoiceData is a PayPalInvoiceData object which contains tax, shipping, and a list of PayPalInvoiceItem objects details.invoiceData = [[PayPalInvoiceData alloc] init]; //invoiceItems is a list of PayPalInvoiceItem objects //NOTE: sum of totalPrice for all items must equal details.subTotal //NOTE: example only shows a single item, but you can have more than one details.invoiceData.invoiceItems = [NSMutableArray array]; PayPalInvoiceItem *item = [[PayPalInvoiceItem alloc] init]; item.totalPrice = details.subTotal; [details.invoiceData.invoiceItems addObject:item]; [payment.receiverPaymentDetails addObject:details]; } [[PayPal getPayPalInst] advancedCheckoutWithPayment:payment]; Can anybody tell me how to do this conversion? Thanks and regards in advance.

    Read the article

  • I get the warning "Format not a string literal and no format arguments" at NSLog -- how can I correc

    - by dsobol
    Hello, I get the warning "Format not a string literal and no format arguments" on the NSLog call in the following block: (void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex { NSLog([NSString stringWithFormat:@"%d", buttonIndex]); } I have read in another post here that this error message indicates an insecure use of NSLog. Could someone point me in the direction of a properly formatted string for this? Thanks for any and all assistance! Regards, Steve O'Sullivan

    Read the article

  • What's the difference between single and double quotes in Objective-C?

    - by Alex Mcp
    I'm working through a book exercise to generate some random serial number, and here's my function: NSString *randomSerialNumber = [NSString stringWithFormat:@"%c%c%c%c%c", '0' + random() % 10, 'A' + random() % 26, '0' + random() % 10, 'A' + random() % 26, '0' + random() % 10]; This works and has an output like: 2J6X7. But before, the 0s and As I had wrapped in double quotes, and an example output was 11764iÒ˜. What did I do wrong my first time around, and why did using single quotes fix it?

    Read the article

  • how to display numbers without garbage numbers?

    - by Medeti Naveen Kumar
    Hi friends, whenever i press the numbers in text filed upto 9 numbers my textfield has taken right values but i press 10 th number.i have found duplicate number. in my header file i declare a pressnumber is "long long int" -(IBAction)press:(id)sender{ pressNumber = pressNumber*10 + (int)[sender tag]; phonenumber.text = [NSString stringWithFormat:@"%d",currentNumber]; } i want to enter a phone number in my textfiled but it is not taken 10 right numbers. Thanking you,

    Read the article

  • Removing time from date format

    - by Prash.......
    Hi, I am developing an application in that i have used DatePicker to pick the date but it gives me date with time .I have converted that format into string, now i just want date from that. How should i do that.Plz suggest me something. Following is my code Snippet. NSDate *selected =[datePicker date]; NSString *dateString = [NSString stringWithFormat:@"%@", selected]; here date picker is object of UIDatePicker.

    Read the article

  • Limit a double to two decimal places

    - by Jacob
    How do I achieve the following conversion from double to a string: 1.4324 => "1.43" 9.4000 => "9.4" 43.000 => "43" ie I want to round to to decimal places but dont want any trailing zeros, ie i dont want 9.4 => "9.40" (wrong) 43.000 => "43.00" (wrong) So this code which I have now doesn't work as it displays excess twos: [NSString stringWithFormat: @"%.2f", total]

    Read the article

  • Obj-C crashes on substringWithRange message

    - by code_burgar
    The following code is making my app crash at line 3 without an error I would recognize or know how to deal with. Any ideas as to what I am doing wrong? NSInteger *match = [str1 intValue] + [str2 intValue]; NSString *strrep = [NSString stringWithFormat:@"%i", match]; label.text = [strrep substringWithRange:NSMakeRange(1,3)];

    Read the article

  • Iphone App deve- Very basic table view but getting errors , trying for 2 days!! just for info using

    - by user342451
    Hi guys, trying to write this code since 2 days now, but i keep getting error, it would be nice if anyone could sort this out, thanks. Basically its the same thing i doing from the tutorial on youtube. awaiting a reply // // BooksTableViewController.m // Mybooks // // import "BooksTableViewController.h" import "BooksDetailViewController.h" import "MYbooksAppDelegate.h" @implementation BooksTableViewController @synthesize BooksArray; @synthesize BooksDetailViewController; /* - (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier { if ((self = [super initWithStyle:style reuseIdentifier:reuseIdentifier])) { // Initialization code } return self; } */ (void)viewDidLoad { [super viewDidLoad]; self.title = NSLocalizedString(@"XYZ",@"GOD is GREAT"); NSMutableArray *array = [[NSArray alloc] initWithObjects:@"H1",@"2",@"3",nil]; self.booksArray = array; [array release]; } /* // Override to allow orientations other than the default portrait orientation. - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { // Return YES for supported orientations return (interfaceOrientation == UIInterfaceOrientationPortrait); } */ (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview // Release anything that's not essential, such as cached data } pragma mark Table view methods (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return 1; } // Customize the number of rows in the table view. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return [self.booksArray count]; } // Customize the appearance of table view cells. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *identity = @"Cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identity]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:identity] autorelease]; } // Set up the cell... cell.textLabel.text = [booksArray objectAtIndex:indexPath.row]; return cell; } /* - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { booksDetailsViewControler *NC = [[booksDetailsViewControler alloc] initWithNibName:@"BooksDetailsView" bundle:nil]; [self.navigationController pushViewController:NC animated:YES]; //[booksDetailViewController changeProductText:[booksArray objectAtIndex:indexPath.row]]; } */ NSInteger row = [indexPath row]; if (self.booksDetailViewController == nil) { BooksiDetailViewController *aCellDetails = [[AartiDetailViewController alloc] initWithNibName:@" BooksDetailViewController" bundle:nil]; self.booksDetailViewController = aCellDetails; [aCellDetails release]; } booksDetailViewController.title = [NSString stringWithFormat:@"%@", [booksArray objectAtIndex:row]]; //DailyPoojaAppDelegate *delegate = [[UIApplication sharedApplication] delegate]; //[delegate.AartiNavController pushViewController:aartiDetailsViewControler animated:YES]; [self.navigationController pushViewController:aartiDetailViewController animated:YES]; } /* NSInteger row = [indexPath row]; if (self.booksDetailsViewControler == nil) { AartiDetailsViewControler *aBookDetail = [[BooksDetailsViewControler alloc] initWithNibName:@"booksDetaislView" bundle:nil]; self.booksDetailsViewControler = aBookDetail; [aBookDetail release]; } booksDetailsViewControler.title = [NSString stringWithFormat:@"%@", [booksArray objectAtIndex:row]]; [self.navigationController pushViewController:booksDetailsViewControler animated:YES]; */ (void)dealloc { [aartiDetailViewController release]; [super dealloc]; } @end

    Read the article

  • Random Number Generator

    - by skinni
    - (IBAction)randomnum{ int randomNumber1 = 1+ arc4random() %(49); label1.text = [NSString stringWithFormat:@"d", randomNumber]; Local declaration of randomNumber hides instance variable. How can i get round this warning? thanks

    Read the article

  • php web services not getting data from iphone application

    - by user317192
    Hi, I am connecting with a php web service from my iphone application, I am doing a simple thing i.e. 1. Getting user inputs for: username password in a text field from the iphone form and sending the same to the PHP Post request web service. At the web service end I receive nothing other than blank fields that are inserted into the MySQL Database....... The code for sample web service is: ***********SAMPLE CODE FOR WEB SERVICES***** mysql_select_db("eventsfast",$con); $username = $_REQUEST['username']; $password = $_REQUEST['password']; echo $username; echo $password; $data = $_REQUEST; $fp = fopen("log.txt", "w"); fwrite($fp, $data['username']); fwrite($fp, $data['password']); $sql="INSERT INTO users(username,password) VALUES('{$username}','{$password}')"; if(!mysql_query($sql,$con)) { die('Error:'.mysql_error()); } echo json_encode("1 record added to users table"); mysql_close($con); echo "test"; ? ***************PHP******** ****** **************IPHONE EVENT CODE******* import "postdatawithphpViewController.h" @implementation postdatawithphpViewController @synthesize userName,password; -(IBAction) postdataid) sender { NSLog(userName.text); NSLog(password.text); NSString * dataTOB=[userName.text stringByAppendingString:password.text]; NSLog(dataTOB); NSData * postData=[dataTOB dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES]; NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]]; NSLog(postLength); NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease]; NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://localhost:8888/write.php"]]; [request setURL:url]; [request setHTTPMethod:@"POST"]; [request setValue:postLength forHTTPHeaderField:@"Content-Length"]; [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; [request setHTTPBody:postData]; NSURLResponse *response; NSError *error; [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]; if(error==nil) NSLog(@"Error is nil"); else NSLog(@"Error is not nil"); NSLog(@"success!"); } Please help.............

    Read the article

  • iOs receivedData from NSURLConnection is nil

    - by yhl
    I was wondering if anyone could point out why I'm not able to capture a web reply. My NSLog shows that my [NSMutableData receivedData] has a length of 0 the entire run of the connection. The script that I hit when I click my login button returns a string. My NSLog result is pasted below, and after that I've pasted both the .h and .m files that I have. NSLog Result 2012-11-28 23:35:22.083 [12548:c07] Clicked on button_login 2012-11-28 23:35:22.090 [12548:c07] theConnection is succesful 2012-11-28 23:35:22.289 [12548:c07] didReceiveResponse 2012-11-28 23:35:22.290 [12548:c07] didReceiveData 2012-11-28 23:35:22.290 [12548:c07] 0 2012-11-28 23:35:22.290 [12548:c07] connectionDidFinishLoading 2012-11-28 23:35:22.290 [12548:c07] 0 ViewController.h #import <UIKit/UIKit.h> @interface ViewController : UIViewController // Create an Action for the button. - (IBAction)button_login:(id)sender; // Add property declaration. @property (nonatomic,assign) NSMutableData *receivedData; @end ViewController.m #import ViewController.h @interface ViewController () @end @implementation ViewController @synthesize receivedData; - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { NSLog(@"didReceiveResponse"); [receivedData setLength:0]; } - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { NSLog(@"didReceiveData"); [receivedData appendData:data]; NSLog(@"%d",[receivedData length]); } - (void)connectionDidFinishLoading:(NSURLConnection *)connection { NSLog(@"connectionDidFinishLoading"); NSLog(@"%d",[receivedData length]); } - (IBAction)button_login:(id)sender { NSLog(@"Clicked on button_login"); NSString *loginScriptURL = [NSString stringWithFormat:@"http://www.website.com/app/scripts/login.php?"]; NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:loginScriptURL]]; NSString *postString = [NSString stringWithFormat:@"&paramUsername=user&paramPassword=pass"]; NSData *postData = [postString dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]; [theRequest setHTTPMethod:@"POST"]; [theRequest setHTTPBody:postData]; // Create the actual connection using the request. NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self]; // Capture the response if (theConnection) { NSLog(@"theConnection is succesful"); } else { NSLog(@"theConnection failed"); } } @end

    Read the article

  • Very basic table view but getting errors

    - by user342451
    Hi guys, trying to write this code since 2 days now, but i keep getting error, it would be nice if anyone could sort this out, thanks. Basically its the same thing i doing from the tutorial on youtube. awaiting a reply // // BooksTableViewController.m // Mybooks // // #import "BooksTableViewController.h" #import "BooksDetailViewController.h" #import "MYbooksAppDelegate.h" @implementation BooksTableViewController @synthesize BooksArray; @synthesize BooksDetailViewController; /* - (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier { if ((self = [super initWithStyle:style reuseIdentifier:reuseIdentifier])) { // Initialization code } return self; } */ - (void)viewDidLoad { [super viewDidLoad]; self.title = NSLocalizedString(@"XYZ",@"GOD is GREAT"); NSMutableArray *array = [[NSArray alloc] initWithObjects:@"H1",@"2",@"3",nil]; self.booksArray = array; [array release]; } /* // Override to allow orientations other than the default portrait orientation. - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { // Return YES for supported orientations return (interfaceOrientation == UIInterfaceOrientationPortrait); } */ - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview // Release anything that's not essential, such as cached data } #pragma mark Table view methods - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return 1; } // Customize the number of rows in the table view. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return [self.booksArray count]; } // Customize the appearance of table view cells. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *identity = @"Cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identity]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:identity] autorelease]; } // Set up the cell... cell.textLabel.text = [booksArray objectAtIndex:indexPath.row]; return cell; } /* - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { booksDetailsViewControler *NC = [[booksDetailsViewControler alloc] initWithNibName:@"BooksDetailsView" bundle:nil]; [self.navigationController pushViewController:NC animated:YES]; //[booksDetailViewController changeProductText:[booksArray objectAtIndex:indexPath.row]]; } */ NSInteger row = [indexPath row]; if (self.booksDetailViewController == nil) { BooksiDetailViewController *aCellDetails = [[AartiDetailViewController alloc] initWithNibName:@" BooksDetailViewController" bundle:nil]; self.booksDetailViewController = aCellDetails; [aCellDetails release]; } booksDetailViewController.title = [NSString stringWithFormat:@"%@", [booksArray objectAtIndex:row]]; //DailyPoojaAppDelegate *delegate = [[UIApplication sharedApplication] delegate]; //[delegate.AartiNavController pushViewController:aartiDetailsViewControler animated:YES]; [self.navigationController pushViewController:aartiDetailViewController animated:YES]; } /* NSInteger row = [indexPath row]; if (self.booksDetailsViewControler == nil) { AartiDetailsViewControler *aBookDetail = [[BooksDetailsViewControler alloc] initWithNibName:@"booksDetaislView" bundle:nil]; self.booksDetailsViewControler = aBookDetail; [aBookDetail release]; } booksDetailsViewControler.title = [NSString stringWithFormat:@"%@", [booksArray objectAtIndex:row]]; [self.navigationController pushViewController:booksDetailsViewControler animated:YES]; */ - (void)dealloc { [aartiDetailViewController release]; [super dealloc]; } @end

    Read the article

  • how to change color of table view title

    - by madhavi
    hello, Can we change the color of the table view title the string which i am showing appears in gray color can we choose color for it .Is there any property of table view title i am not asking for table view header or footer i mean the title - (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section { // Keep space in the following line ........ DONT REMOVE return [NSString stringWithFormat:@"Select your service:"]; }

    Read the article

  • intialization with a nibFIle failed

    - by zp26
    Hi, I have a problem. I try to initialize a variabile in a classViewController created inside a xib file. I try with the code below but when i append a object to array, these array isn't initialized. Can you help me? thanks and sorry for my english. #import <UIKit/UIKit.h> @interface AccelerometroViewController : UIViewController <UIAccelerometerDelegate, UITextFieldDelegate, UIAlertViewDelegate>{ //..... NSMutableArray *arrayPosizioni; NSMutableArray *arrayPosizioniCorrenti; NSString *nomePosizioneCorrente; } -(IBAction)salvaPosizione; //... @property (nonatomic, assign) NSMutableArray *arrayPosizioni; @property (nonatomic, assign) NSMutableArray *arrayPosizioniCorrenti; @property (nonatomic, assign) NSString *nomePosizioneCorrente; @end #import "AccelerometroViewController.h" #import "Position.h" @implementation AccelerometroViewController float actualX; float actualY; float actualZ; @synthesize arrayPosition; @synthesize arrayCurrentPosition; @synthesize nameCurrentPosition; -(id)init { self = [super init]; if (self != nil) { arrayPosition = [[NSMutableArray alloc]init]; arrayCurrentPosition = [[NSMutableArray alloc]init]; nameCurrentPosition = [NSString stringWithFormat:@"noPosition"]; actualX = 0; actualY = 0; actualZ = 0; } return self; } -(void)updateTextView:(NSString*)nomePosizione { NSString *string = [NSString stringWithFormat:@"%@", nameCurrentPosition]; textEvent.text = [textEvent.text stringByAppendingString:@"\n"]; textEvent.text = [textEvent.text stringByAppendingString:string]; } -(IBAction)savePosition{ Posizione *newPosition; newPosition = [[Position alloc]init]; if([newPosition setValue:(NSString*)fieldNomePosizione.text:(float)actualX:(float)actualY:(float)actualZ]){ //setValue is a method of Position. I'm sure that this method is correct UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Salvataggio Posizione" message:@"Posizione salvata con successo" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:nil]; [alert show]; [alert release]; [arrayPosition addObject:newPosition]; } else{ UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Salvataggio osizione" message:@"Errore nel salvataggio" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:nil]; [alert show]; [alert release]; } } - (void) initialise { arrayPosition = [[NSMutableArray alloc] init]; arrayCurrentPosition = [[NSMutableArray alloc] init]; nameCurrentPosition = @"noPosition"; actualX = 0; actualY = 0; actualZ = 0; } - (id)initWithNibName:(NSString *)nibName bundle:(NSBundle *)nibBundle { if (self = [super initWithNibName:nibName bundle:bundle]) { [self initialise]; } }

    Read the article

  • problem with get http request from IPhone

    - by user317192
    Hi, I am writing a sample PHP Web Service that is sending GET Http request from the iphone to the web server. The server side code is returning JSON Data to iphone, the server side code looks like: function getUsers(){ $con=mysql_connect("localhost","root","123456") or die(mysql_error()); if(!mysql_select_db("eventsfast",$con)) { echo "Unable to connect to DB"; exit; } $sql="SELECT * from users"; $result=mysql_query($sql); if(!$result) { die('Could not successfully run query Error:'.mysql_error()); } $data = array(); while($row = mysql_fetch_assoc($result)){ $data['username'][] = $row['username']; $data['password'][]= $row['password']; } mysql_close($con); //print_r(json_encode($data)); //return (json_encode($data)); return json_encode('success'); } getUsers(); ? Its a simple code that Fetches all the data from the user table and send it to the iphone application. *****************************************************IPHONE APPLICATION (void)viewDidLoad { [super viewDidLoad]; responseData = [[NSMutableData data] retain]; NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://localhost:8888/GetData.php"]]; [[NSURLConnection alloc] initWithRequest:request delegate:self]; } (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { [responseData setLength:0]; } (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { [responseData appendData:data]; } (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { label.text = [NSString stringWithFormat:@"Connection failed: %@", [error description]]; } (void)connectionDidFinishLoading:(NSURLConnection *)connection { [connection release]; NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding]; [responseData release]; NSError *error; SBJSON *json = [[SBJSON new] autorelease]; NSArray *luckyNumbers = [json objectWithString:responseString error:&error]; [responseString release]; if (luckyNumbers == nil) label.text = [NSString stringWithFormat:@"JSON parsing failed: %@", [error localizedDescription]]; else { NSMutableString *text = [NSMutableString stringWithString:@"Lucky numbers:\n"]; for (int i = 0; i < [luckyNumbers count]; i++) [text appendFormat:@"%@\n", [luckyNumbers objectAtIndex:i]]; NSLog(text); label.text = text; } } ********************PROBLEM**************** The problem is that nothing is coming on iphone side of the application........... the response doesn't contains anything.............. Please help..............

    Read the article

  • constructor in objective c

    - by zp26
    HI, I have create my iPhone apps but i have a problem. I have a classViewController where i have implemented my program. I must alloc 3 NSMutableArray but i don't want do it in a grapich methods. There isn't a constructor like java for my class? Thanks so much and sorry for my english XP // I want put it in a method like constructor java arrayPosizioni = [[NSMutableArray alloc]init]; nomePosizioneCorrente = [NSString stringWithFormat:@"noPosition"];

    Read the article

  • How to read file.xml from resources to NSString with format?

    - by falkon
    Actually I have such a code: NSString *path = [[NSBundle mainBundle] pathForResource: @"connect" ofType: @"xml"]; NSError *error = nil; NSString *data = [NSString stringWithContentsOfFile: path encoding: NSUTF8StringEncoding error: &error]; NSString *message = [NSString stringWithFormat:data, KEY, COUNTRY_ID]; which reads the connect.xml from resources. But on the formating the string (message) APP quits without displaying any errors. How can I read file.xml from resources to NSString with format?

    Read the article

  • % operator for time calculation

    - by Chris
    I am trying to display minutes and seconds based on a number of seconds. I have: float seconds = 200; float mins = seconds / 60.0; float sec = mins % 60.0; [timeIndexLabel setText:[NSString stringWithFormat:@"%.2f , %.2f", mins,seconds]]; But I get an error: invalid operands of types 'float' and 'double' to binary 'operator%' And I don't understand why... Can someone throw me a bone!?

    Read the article

  • escape % in objective c

    - by Saurabh
    Hello All, I want to make an sql statement - sqlStatement = [NSString stringWithFormat:@"SELECT * FROM movies where title like '%%@%'",searchKeyword]; But sqlStatement is becoming - "SELECT * FROM movies where title like '%@'" I want to make it "SELECT * FROM movies where title like '%searchKeyword%'" How can I escape the "%" character? Thanks

    Read the article

  • Crash: iPhone Threading with Blocks

    - by jtbandes
    I have some convenience methods set up for threading with blocks (using PLBlocks). Then in the main portion of my code, I call the method -fetchArrivalsForLocationIDs:callback:errback:, which runs some web API calls in the background. Here's the problem: when I comment out the 2 NSAutoreleasePool-related lines in JTBlockThreading.m, of course I get lots of Object 0x6b31280 of class __NSArrayM autoreleased with no pool in place - just leaking errors. However, if I uncomment them, the app frequently crashes on the [pool release]; line, sometimes saying malloc: *** error for object 0x6e3ae10: pointer being freed was not allocated" *** set a breakpoint in malloc_error_break to debug. I assume I've made a horrible mistake/assumption in threading somewhere, but can anyone figure out what exactly the problem is? // JTBlockThreading.h #import <Foundation/Foundation.h> #import <PLBlocks/Block.h> #define JT_BLOCKTHREAD_BACKGROUND [self invokeBlockInBackground:^{ #define JT_BLOCKTHREAD_MAIN [self invokeBlockOnMainThread:^{ #define JT_BLOCKTHREAD_END }]; #define JT_BLOCKTHREAD_BACKGROUND_END_WAIT } waitUntilDone:YES]; @interface NSObject (JTBlockThreading) - (void)invokeBlockInBackground:(void (^)())block; - (void)invokeBlockOnMainThread:(void (^)())block; - (void)invokeBlockOnMainThread:(void (^)())block waitUntilDone:(BOOL)wait; - (void)invokeBlock:(void (^)())block; @end // JTBlockThreading.m #import "JTBlockThreading.h" @implementation NSObject (JTBlockThreading) - (void)invokeBlockInBackground:(void (^)())block { [self performSelectorInBackground:@selector(invokeBlock:) withObject:[block copy]]; } - (void)invokeBlockOnMainThread:(void (^)())block { [self invokeBlockOnMainThread:block waitUntilDone:NO]; } - (void)invokeBlockOnMainThread:(void (^)())block waitUntilDone:(BOOL)wait { [self performSelectorOnMainThread:@selector(invokeBlock:) withObject:[block copy] waitUntilDone:wait]; } - (void)invokeBlock:(void (^)())block { //NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; block(); [block release]; //[pool release]; } @end - (void)fetchArrivalsForLocationIDs:(NSString *)locIDs callback:(JTWSCallback)callback errback:(JTWSErrback)errback { JT_PUSH_NETWORK(); JT_BLOCKTHREAD_BACKGROUND NSError *error = nil; // Create API call URL NSURL *url = [NSURL URLWithString: [NSString stringWithFormat:@"%@/arrivals/appID/%@/locIDs/%@", TRIMET_BASE_URL, appID, locIDs]]; if (!url) { JT_BLOCKTHREAD_MAIN errback(@"That’s not a valid Stop ID!"); JT_POP_NETWORK(); JT_BLOCKTHREAD_END return; } // Call API NSData *data = [NSData dataWithContentsOfURL:url options:0 error:&error]; if (!data) { JT_BLOCKTHREAD_MAIN errback([NSString stringWithFormat: @"Had trouble downloading the arrival data! %@", [error localizedDescription]]); JT_POP_NETWORK(); JT_BLOCKTHREAD_END return; } CXMLDocument *doc = [[CXMLDocument alloc] initWithData:data options:0 error:&error]; if (!doc) { JT_BLOCKTHREAD_MAIN // TODO: further error description // (TouchXML doesn't provide information with the error) errback(@"Had trouble reading the arrival data!"); JT_POP_NETWORK(); JT_BLOCKTHREAD_END return; } NSArray *nodes = nil; CXMLElement *resultSet = [doc rootElement]; // Begin building the response model JTWSResponseArrivalData *response = [[[JTWSResponseArrivalData alloc] init] autorelease]; response.queryTime = [NSDate JT_dateWithTriMetWSTimestamp: [[resultSet attributeValueForName:@"queryTime"] longLongValue]]; if (!response.queryTime) { // TODO: further error check? NSLog(@"Hm, query time is nil in %s... response %@, resultSet %@", __PRETTY_FUNCTION__, response, resultSet); } nodes = [resultSet nodesForXPath:@"//arrivals:errorMessage" namespaceMappings:namespaceMappings error:&error]; if ([nodes count] > 0) { NSString *message = [[nodes objectAtIndex:0] stringValue]; response.errorMessage = message; // TODO: this probably won't be used... JT_BLOCKTHREAD_MAIN errback([NSString stringWithFormat: @"TriMet error: “%@”", message]); JT_POP_NETWORK(); JT_BLOCKTHREAD_END return; } // Build location models nodes = [resultSet nodesForXPath:@"/arrivals:location" namespaceMappings:namespaceMappings error:&error]; if ([nodes count] <= 0) { NSLog(@"Hm, no locations returned in %s... xpath error %@, response %@, resultSet %@", __PRETTY_FUNCTION__, error, response, resultSet); } NSMutableArray *locations = [NSMutableArray arrayWithCapacity:[nodes count]]; for (CXMLElement *loc in nodes) { JTWSLocation *location = [[[JTWSLocation alloc] init] autorelease]; location.desc = [loc attributeValueForName:@"desc"]; location.dir = [loc attributeValueForName:@"dir"]; location.position = [[[CLLocation alloc] initWithLatitude:[[loc attributeValueForName:@"lat"] doubleValue] longitude:[[loc attributeValueForName:@"lng"] doubleValue]] autorelease]; location.locID = [[loc attributeValueForName:@"locid"] integerValue]; } // Build arrival models nodes = [resultSet nodesForXPath:@"/arrivals:arrival" namespaceMappings:namespaceMappings error:&error]; if ([nodes count] <= 0) { NSLog(@"Hm, no arrivals returned in %s... xpath error %@, response %@, resultSet %@", __PRETTY_FUNCTION__, error, response, resultSet); } NSMutableArray *arrivals = [[NSMutableArray alloc] initWithCapacity:[nodes count]]; for (CXMLElement *arv in nodes) { JTWSArrival *arrival = [[JTWSArrival alloc] init]; arrival.block = [[arv attributeValueForName:@"block"] integerValue]; arrival.piece = [[arv attributeValueForName:@"piece"] integerValue]; arrival.locID = [[arv attributeValueForName:@"locid"] integerValue]; arrival.departed = [[arv attributeValueForName:@"departed"] boolValue]; // TODO: verify arrival.detour = [[arv attributeValueForName:@"detour"] boolValue]; // TODO: verify arrival.direction = (JTWSRouteDirection)[[arv attributeValueForName:@"dir"] integerValue]; arrival.estimated = [NSDate JT_dateWithTriMetWSTimestamp: [[arv attributeValueForName:@"estimated"] longLongValue]]; arrival.scheduled = [NSDate JT_dateWithTriMetWSTimestamp: [[arv attributeValueForName:@"scheduled"] longLongValue]]; arrival.fullSign = [arv attributeValueForName:@"fullSign"]; arrival.shortSign = [arv attributeValueForName:@"shortSign"]; NSString *status = [arv attributeValueForName:@"status"]; if ([status isEqualToString:@"estimated"]) { arrival.status = JTWSArrivalStatusEstimated; } else if ([status isEqualToString:@"scheduled"]) { arrival.status = JTWSArrivalStatusScheduled; } else if ([status isEqualToString:@"delayed"]) { arrival.status = JTWSArrivalStatusDelayed; } else if ([status isEqualToString:@"canceled"]) { arrival.status = JTWSArrivalStatusCanceled; } else { NSLog(@"Unknown arrival status %s in %@... response %@, arrival %@", status, __PRETTY_FUNCTION__, response, arv); } NSArray *blockPositions = [arv nodesForXPath:@"/arrivals:blockPosition" namespaceMappings:namespaceMappings error:&error]; if ([blockPositions count] > 1) { // The schema allows for any number of blockPosition elements, // but I'm really not sure why... NSLog(@"Hm, more than one blockPosition in %s... response %@, arrival %@", __PRETTY_FUNCTION__, response, arv); } if ([blockPositions count] > 0) { CXMLElement *bpos = [blockPositions objectAtIndex:0]; JTWSBlockPosition *blockPosition = [[JTWSBlockPosition alloc] init]; blockPosition.reported = [NSDate JT_dateWithTriMetWSTimestamp: [[bpos attributeValueForName:@"at"] longLongValue]]; blockPosition.feet = [[bpos attributeValueForName:@"feet"] integerValue]; blockPosition.position = [[[CLLocation alloc] initWithLatitude:[[bpos attributeValueForName:@"lat"] doubleValue] longitude:[[bpos attributeValueForName:@"lng"] doubleValue]] autorelease]; NSString *headingStr = [bpos attributeValueForName:@"heading"]; if (headingStr) { // Valid CLLocationDirections are > 0 CLLocationDirection heading = [headingStr integerValue]; while (heading < 0) heading += 360.0; blockPosition.heading = heading; } else { blockPosition.heading = -1; // indicates invalid heading } NSArray *tripData = [bpos nodesForXPath:@"/arrivals:trip" namespaceMappings:namespaceMappings error:&error]; NSMutableArray *trips = [[NSMutableArray alloc] initWithCapacity:[tripData count]]; for (CXMLElement *tripDatum in tripData) { JTWSTrip *trip = [[JTWSTrip alloc] init]; trip.desc = [tripDatum attributeValueForName:@"desc"]; trip.destDist = [[tripDatum attributeValueForName:@"destDist"] integerValue]; trip.direction = (JTWSRouteDirection)[[tripDatum attributeValueForName:@"dir"] integerValue]; trip.pattern = [[tripDatum attributeValueForName:@"pattern"] integerValue]; trip.progress = [[tripDatum attributeValueForName:@"progress"] integerValue]; trip.route = [[tripDatum attributeValueForName:@"route"] integerValue]; [trips addObject:trip]; [trip release]; } blockPosition.trips = trips; [trips release]; NSArray *layoverData = [bpos nodesForXPath:@"/arrivals:layover" namespaceMappings:namespaceMappings error:&error]; NSMutableArray *layovers = [[NSMutableArray alloc] initWithCapacity:[layoverData count]]; for (CXMLElement *layoverDatum in layoverData) { JTWSLayover *layover = [[JTWSLayover alloc] init]; layover.start = [NSDate JT_dateWithTriMetWSTimestamp: [[layoverDatum attributeValueForName:@"start"] longLongValue]]; layover.end = [NSDate JT_dateWithTriMetWSTimestamp: [[layoverDatum attributeValueForName:@"end"] longLongValue]]; // TODO: it seems the API can send a <location> inside a layover (undocumented)... support? [layovers addObject:layover]; [layover release]; } blockPosition.layovers = layovers; [layovers release]; arrival.blockPosition = blockPosition; [blockPosition release]; } [arrivals addObject:arrival]; [arrival release]; } // Add arrivals to corresponding locations for (JTWSLocation *loc in locations) { loc.arrivals = [arrivals selectWithBlock:^BOOL (id arv) { return loc.locID == ((JTWSArrival *)arv).locID; }]; } [arrivals release]; response.locations = locations; [locations release]; // Build route status models (used in inclement weather) nodes = [resultSet nodesForXPath:@"/arrivals:routeStatus" namespaceMappings:namespaceMappings error:&error]; NSMutableArray *routeStatuses = [NSMutableArray arrayWithCapacity:[nodes count]]; for (CXMLElement *stat in nodes) { JTWSRouteStatus *status = [[JTWSRouteStatus alloc] init]; status.route = [[stat attributeValueForName:@"route"] integerValue]; NSString *statusStr = [stat attributeValueForName:@"status"]; if ([statusStr isEqualToString:@"estimatedOnly"]) { status.status = JTWSRouteStatusTypeEstimatedOnly; } else if ([statusStr isEqualToString:@"off"]) { status.status = JTWSRouteStatusTypeOff; } else { NSLog(@"Unknown route status type %s in %@... response %@, routeStatus %@", status, __PRETTY_FUNCTION__, response, stat); } [routeStatuses addObject:status]; [status release]; } response.routeStatuses = routeStatuses; [routeStatuses release]; JT_BLOCKTHREAD_MAIN callback(response); JT_POP_NETWORK(); JT_BLOCKTHREAD_END JT_BLOCKTHREAD_END }

    Read the article

  • how to stop the array of sprite in cocos2d?

    - by prakash s
    I am devoloping the bubble shooter game in cocos2d how to stop the sprite movement at the center of the game scene in my game bec i want to shoot the bubble after stopping the movenent at certain position here is my code -(void)addTarget { CGSize winSize = [[CCDirector sharedDirector] winSize]; NSMutableArray * movableSprites = [[NSMutableArray alloc] init]; NSArray *images = [NSArray arrayWithObjects:@"1.png", @"2.png", @"3.png", @"4.png",@"5.png", @"6.png", @"7.png",@"8.png" ,nil]; for(int i = 0; i < images.count; ++i) { int index = (arc4random() % 8)+1; NSString *image = [NSString stringWithFormat:@"%d.png", index]; CCSprite*target = [CCSprite spriteWithFile:image]; // generate random number based on size of array (array size is larger than 10) float offsetFraction = ((float)(i+1))/(images.count+1); //target.position = ccp(winSize.width*offsetFraction, winSize.height/2); target.position = ccp(350*offsetFraction, 460); [self addChild:target]; [movableSprites addObject:target]; id actionMove = [CCMoveTo actionWithDuration:10 position:ccp(350*offsetFraction, 100)]; id actionMoveDone = [CCCallFuncN actionWithTarget:self selector:@selector(spriteMoveFinished:)]; [target runAction:[CCSequence actions:actionMove, actionMoveDone, nil]]; } here bubbles are moving from top to bottom but after 5 rows my bubble movement should be stop so please help me to get that logic

    Read the article

  • Change collision action

    - by PatrickR
    I have a collision detection and its working fine, the problem is, that whenever my "bird" is hitting a "cloud", the cloud dissapers and i get some points. The same happens for the "sol" which it should, but not with the clouds. How can this be changed ? ive tryed a lot, but can seem to figger it out. Collision Code - (void)update:(ccTime)dt { bird.position = ccpAdd(bird.position, skyVelocity); NSMutableArray *projectilesToDelete = [[NSMutableArray alloc] init]; for (CCSprite *bird in _projectiles) { bird.anchorPoint = ccp(0, 0); CGRect absoluteBox = CGRectMake(bird.position.x, bird.position.y, [bird boundingBox].size.width, [bird boundingBox].size.height); NSMutableArray *targetsToDelete = [[NSMutableArray alloc] init]; for (CCSprite *cloudSprite in _targets) { cloudSprite.anchorPoint = ccp(0, 0); CGRect absoluteBox = CGRectMake(cloudSprite.position.x, cloudSprite.position.y, [cloudSprite boundingBox].size.width, [cloudSprite boundingBox].size.height); if (CGRectIntersectsRect([bird boundingBox], [cloudSprite boundingBox])) { [targetsToDelete addObject:cloudSprite]; } } for (CCSprite *solSprite in _targets) { solSprite.anchorPoint = ccp(0, 0); CGRect absoluteBox = CGRectMake(solSprite.position.x, solSprite.position.y, [solSprite boundingBox].size.width, [solSprite boundingBox].size.height); if (CGRectIntersectsRect([bird boundingBox], [solSprite boundingBox])) { [targetsToDelete addObject:solSprite]; score += 50/2; [scoreLabel setString:[NSString stringWithFormat:@"%d", score]]; } } // NÅR SKYEN BLIVER RAMT AF FUGLEN for (CCSprite *cloudSprite in targetsToDelete) { //[_targets removeObject:cloudSprite]; //[self removeChild:cloudSprite cleanup:YES]; } // NÅR SOLEN BLIVER RAMT AF FUGLEN for (CCSprite *solSprite in targetsToDelete) { [_targets removeObject:solSprite]; [self removeChild:solSprite cleanup:YES]; } if (targetsToDelete.count > 0) { [projectilesToDelete addObject:bird]; } [targetsToDelete release]; } // NÅR FUGLEN BLIVER RAMT AF ALT ANDET for (CCSprite *bird in projectilesToDelete) { //[_projectiles removeObject:bird]; //[self removeChild:bird cleanup:YES]; } [projectilesToDelete release]; }

    Read the article

< Previous Page | 6 7 8 9 10 11 12 13 14 15 16 17  | Next Page >