Search Results

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

Page 21/25 | < Previous Page | 17 18 19 20 21 22 23 24 25  | Next Page >

  • Cant access NString after callback in [NSURLConnection sendSynchronousRequest]

    - by John ClearZ
    Hi I am trying to get a cookie from a site which I can do no problem. The problem arises when I try and save the cookie to a NSString in a holder class or anywhere else for that matter and try and access it outside the delegate method where it is first created. - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { int i; NSString* c; NSArray* all = [NSHTTPCookie cookiesWithResponseHeaderFields:[response allHeaderFields] forURL:[NSURL URLWithString:@"http://johncleary.net"]]; //NSLog(@"RESPONSE HEADERS: \n%@", [response allHeaderFields]); for (i=0;i<[all count];i++) { NSHTTPCookie* cc = [all objectAtIndex: i]; c = [NSString stringWithFormat: @"%@=%@", [cc name], [cc value]]; [Cookie setCookie: c]; NSLog([Cookie cookie]) // Prints the cookie fine. } [receivedData setLength:0]; } I can see and print the cookie when I am in the method but I cant when trying to access it form anywhere else even though it gets stored in the holder class @interface Cookie : NSObject { NSString* cookie; } + (NSString*) cookie; + (void) setCookie: (NSString*) cookieValue; @end int main (void) { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; JCLogin* login; login = [JCLogin new]; [login DoLogin]; NSLog([Cookie cookie]); // Crashes the program [pool drain]; return 0; }

    Read the article

  • Getting JSON object from php authentication objective c

    - by iError
    I am trying to authenticate using the below code NSString *urlAsString =[NSString stringWithFormat:@"http://www.myurl.com/abc/authenticate.php"]; NSURL *url = [NSURL URLWithString:urlAsString]; NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url]; [urlRequest setTimeoutInterval:30.0f]; [urlRequest setHTTPMethod:@"POST"]; [urlRequest addValue:@"test" forHTTPHeaderField:@"m_username" ]; [urlRequest addValue:@"123" forHTTPHeaderField:@"m_password" ]; [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self]; NSOperationQueue *queue = [[NSOperationQueue alloc] init]; [NSURLConnection sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse *response,NSData *data, NSError *error) { if ([data length] >0 && error == nil){ html = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; NSLog(@"HTML = %@", html); receivedData = [NSMutableData data]; } else if ([data length] == 0 && error == nil){ NSLog(@"Nothing was downloaded."); } else if (error != nil){ NSLog(@"Error happened = %@", error); } }]; // Start loading data NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self]; if (theConnection) { // Create the NSMutableData to hold the received data receivedData = [NSMutableData data]; } else { // Inform the user the connection failed. } My username password is correct, I think I am not making the proper call thats why I dont get the desired results and the web service is receiving the null parameters. What can be the issue? Any help appreciated.

    Read the article

  • Custom Cell over lapping.

    - by user338322
    I am trying to use a custom cell, My custom cell is of size 320*220 pixels. My table size is 320* by 1500 which is large enough I have set custom cell's view in scale to fill mode. But when i fill the table using custom cell all i see is first row. i have total four rows to be filld in a custom way. but they gets overlapped and i can not see any of the table.. They do look, but overlapped, Any hints .. about why its happening Do i need to make changes into nib? -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ static NSString *CellIdentifier = @"CustomCell"; CustomCell *cell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"CustomCell" owner:self options:nil]; for (id oneObject in nib) if ([oneObject isKindOfClass:[CustomCell class]]) cell = (CustomCell *)oneObject; } cell.iconImage.image = [UIImage imageNamed:[NSString stringWithFormat:@"beach%d.jpg",indexPath.row+1]]; cell.title.text=[[RArrray objectAtIndex:indexPath.row] objectForKey:@"Beach"]; return cell; }

    Read the article

  • How to play sound automatically when scrolling to the next page?

    - by viper15
    I'm using Page Control example from Apple. I want to be able to scroll horizontally to certain page and get the sound automatically play when viewing that page? And then sound stop when viewing the other page? So, for example. On page 1, i have some texts. When i go to the next page which is on page 2, i want sound to be automatically play and stop when i go to page 3. I'm planning to use If statements (since it's not that many pages) to determine which page will get the sound. My question is simple. How do you get the sound play automatically when viewing certain page? By the way, I'm planning to use System Sound. I know how to play the sound using button. But how do you get it automatically - start when certain page appear and stop when moving to the next page. Thank you in advance! Edited: I put in this code in ViewDidLoad but the sound played on sooner before it reach the page intended: // Set the label and background color when the view has finished loading. - (void)viewDidLoad { pageNumberLabel.text = [NSString stringWithFormat:@"Page %d", pageNumber + 1]; self.view.backgroundColor = [MyViewController pageControlColorWithIndex:pageNumber]; if (pageNumber == 3) { NSString *path = [[NSBundle mainBundle] pathForResource:@"crunch" ofType:@"wav"]; SystemSoundID soundID; AudioServicesCreateSystemSoundID((CFURLRef)[NSURL fileURLWithPath:path], &soundID); AudioServicesPlaySystemSound(soundID); } }

    Read the article

  • How to get a UIAlertView's result??

    - by cocos2dbeginner
    Hi, I implemented the gamekit. All works fine now. But if the user presses on send the data will instantly send to the other iphone/ipod/ipad and it will instantly written. So now i wanted to implemenr a confirm screen for the receiver. In my receiveData method (from the gamekit) i have an array. If the user presses yes the array will be written into a file.if not it wont be written into a file. #pragma mark - #pragma mark - GKreceiveData - (void) receiveData:(NSData *)data fromPeer:(NSString *)peer inSession: (GKSession *)session context:(void *)context { NSDictionary *dict = [NSKeyedUnarchiver unarchiveObjectWithData:data]; UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Incoming Set" message:[NSString stringWithFormat:@"%@ wants to send you a Set named: \n\n %@",[session displayNameForPeer:peer], [dict valueForKey:@"SetName"]] delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK", nil]; [alert show]; [alert release]; } - (void)alertView:(UIAlertView *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex { // the user clicked one of the OK/Cancel buttons if (buttonIndex == 0) { //NSLog(@"ok"); //this should happen if the user presses on ok on the alertview. [dataArray addObject:dict]; //i can't acess "dict" } else { //NSLog(@"cancel"); } } Do you see the problem?? What can I do??

    Read the article

  • UIViewController maintains state after being nilled

    - by Eric
    In my app, I made a BookViewController class that displays and animates the pages of a book and a MainMenuViewController class that displays a set of books the user can read. In the latter class, when the user taps on one of the books, a function is called that should create a completely new instance of BookViewController, but for some reason the instance maintains its state (i.e. it resumes from the page the user left off). How can this be if I set it to nil? What am I missing here? (Note that I'm using ARC). MainMenuViewController.m @interface MainMenuViewController () @property (strong) BookViewController *bookViewController; @end @implementation MainMenuViewController @synthesize bookViewController; -(void)bookTapped:(UIButton *)sender{ NSString *bookTitle; if(sender == book1button) bookTitle = @"book1"; else if(sender == book2button) bookTitle = @"book2"; bookViewController = nil; bookViewController = [[BookViewController alloc] initWithBookTitle:bookTitle]; [self presentViewController:bookViewController animated:YES completion:nil]; } BookViewController.h @interface BookViewController : UIViewController -(id)initWithBookTitle:(NSString *)bookTitle; @end BookViewController.m @implementation BookViewController -(id)initWithBookTitle:(NSString *)theBookTitle{ self = [super init]; if(self){ bookTitle = [NSString stringWithFormat:@"%@", theBookTitle]; [self setModalTransitionStyle:UIModalTransitionStyleCrossDissolve]; NSLog(@"init a BookViewController with bookTitle: %@", bookTitle); } return self; } Every time a book is tapped, bookTapped: is called, and thee console always prints: 2012-08-31 16:29:51.750 AppName[25713:c07] init a BookViewController with bookTitle: book1 So if a new instance of BookViewController is being created, how come it seems to be returning the old one?

    Read the article

  • How to take a NSString such as, "0+1+2", get the sum of those and create new string. Obj-C

    - by Ace Legend
    Alright. My app has a text field and next to it are two buttons (Plus button and Equals button). When you press the "Plus" button, it takes the text inside of the textField and adds a "+" to it. Code below: - (IBAction)plusButtonPressed:(id)sender { NSString *plusString = @"+"; NSString *inputString = carbsField.text; NSString *outputString = [NSString stringWithFormat:@"%@%@",inputString,plusString]; NSLog(@"%@",outputString); [carbsField setText:outputString]; } I will eventually make that more intelligent so that I can't put two pluses or whatever. Anyway, then I want the equal button to take whatever is in the textField, which should look something like: "23+54+2.2" and get the sum of those values. I believe I know how to take an Integer and make it a String, but I want to verify it: int *value = 56; NSString *string = @"%d",value; Well, if anyone can show me how to do this, I would be very appreciative. Thanks. EDIT At the moment, I have not tried anything. This is because I do not know where to start. I have an idea of what to do, but I do not know how to execute it. I believe I need to get all characters before a "+" convert them into int and then get the sum of some array of those values.

    Read the article

  • Increase content size of UIWebView using Javascript

    - by Sam
    Hi folks, I have a translucent toolbar over the bottom of my UIWebView. The trouble is, if there is a link at the bottom of the page, I can't press it because the webview will always bounce back down to the bottom. I don't want to shrink the webview and use a solid colour toolbar, and UIWebViews interface doesn't open much up. What I would like to do, ideally, is to actually increase the size of the web page by one toolbar height, so that I can scroll that extra bit and have all the content above the toolbar, but when scrolling down I will be able to see the page content through the toolbar. I could use the stringByEvaluatingJavaScriptFromString: function of UIWebView. I'm very rusty on JavaScript- is it possible for me to do this? Increase the window height or something? I tried: [webView stringByEvaluatingJavaScriptFromString: [NSString stringWithFormat:@"window.resizeBy(0,%d);", TOOLBAR_HEIGHT] ]; but it didn't do anything. Any pointers welcome. Thanks.

    Read the article

  • Creating UIButtons

    - by Ralphonzo
    During loadView I am creating 20 UIButtons that I would like to change the title text of depending on the state of a UIPageControl. I have a pre-save plist that is loaded into a NSArray called arrChars on the event of the current page changing, I set the buttons titles to their relevant text title from the array. The code that does this is: for (int i = 1; i < (ButtonsPerPage + 1); i++) { UIButton *uButton = (UIButton *)[self.view viewWithTag:i]; if(iPage == 1) { iArrPos = (i - 1); } else { iArrPos = (iPage * ButtonsPerPage) + (i - 1); } [uButton setAlpha:0]; NSLog(@"Trying: %d of %d", iArrPos, [self.arrChars count]); if (iArrPos >= [self.arrChars count]) { [uButton setTitle: @"" forState: UIControlStateNormal]; } else { NSString *value = [[NSString alloc] initWithFormat:@"%@", [self.arrChars objectAtIndex:iArrPos]]; NSLog(@"%@", value); [uButton setTitle: [[NSString stringWithFormat:@"%@", value] forState: UIControlStateNormal]; [value release]; //////Have tried: //////[uButton setTitle: value forState: UIControlStateNormal]; //////Have also tried: //////[uButton setTitle: [self.arrChars objectAtIndex:iArrPos] forState: UIControlStateNormal]; //////Have also also tried: //////[uButton setTitle: [[self.arrChars objectAtIndex:iArrPos] autorelease] forState: UIControlStateNormal]; } [uButton setAlpha:1]; } When setting the Title of a button it does not appear to be autoreleasing the previous title and the allocation goes up and up. What am I doing wrong? I have been told before that tracking things by allocations is a bad way to chase leaks because as far as I can see, the object is not leaking in Instruments but my total living allocations continue to climb until I get a memory warning. If there is a better way to track there I would love to know.

    Read the article

  • Method invoked but not returning anything

    - by or azran
    i am calling this method from a touch in UITableViewCell , -(void)PassTitleandiMageByindex:(NSString *)number{ NSLog(@"index : %d",number.intValue); NSArray *objectsinDictionary = [[[NSArray alloc]init]autorelease]; objectsinDictionary = [[DataManeger sharedInstance].sortedArray objectAtIndex:number.intValue]; if ([objectsinDictionary count] > 3) { ProductLabel = [objectsinDictionary objectAtIndex:3]; globaliMageRef = [objectsinDictionary objectAtIndex:2]; [self performSegueWithIdentifier:@"infoseg" sender:self]; }else{ mQid = [objectsinDictionary objectAtIndex:1]; globaliMageRef = [objectsinDictionary objectAtIndex:2]; [mIQEngines Result:mQid]; NSLog(@"mQid : %@ Global : %@",mQid,globaliMageRef); }} Problem:- i am trying to get the same functionality programmatically by calling [self PassTitleandiMageByindex:stringNumber]; when i am calling this programmatically i can see the debug log getting in the place it should be, but nothing happens (by pressing the UITableViewCellon the screen) here is how it turns on by touch, - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{ [tableView deselectRowAtIndexPath:indexPath animated:YES]; NSString *st = [NSString stringWithFormat:@"%d",[indexPath row]]; [self PassTitleandiMageByindex:st];} I have also tried to call the table-view delegate by :[[Tview delegate] tableView:Tview didSelectRowAtIndexPath:selectedCellIndexPath]; but, nothing happened.

    Read the article

  • Obj-C Sending Messages Between Classes

    - by user544359
    I'm a newbie in iPhone Programming. I'm trying to send a message from one view controller to another. The idea is that viewControllerA takes information from the user and sends it to viewControllerB. viewControllerB is then supposed to display the information in a label. viewControllerA.h #import <UIKit/UIKit.h> @interface viewControllerA : UIViewController { int num; } -(IBAction)do; @end viewControllerA.m #import "viewControllerA.h" #import "viewControllerB.h" @implementation viewControllerA - (IBAction)do { //initializing int for example num = 2; viewControllerB *viewB = [[viewControllerB alloc] init]; [viewB display:num]; [viewB release]; //viewA is presented as a ModalViewController, so it dismisses itself to return to the //original view, i know it is not efficient [self dismissModalViewControllerAnimated:YES]; } - (void)dealloc { [super dealloc]; } @end viewControllerB.h #import <UIKit/UIKit.h> @interface viewControllerB : UIViewController { IBOutlet UILabel *label; } - (IBAction)openA; - (void)display:(NSInteger)myNum; @end viewControllerB.m #import "viewControllerB.h" #import "viewControllerA.h" @implementation viewControllerB - (IBAction)openA { //presents viewControllerA when a button is pressed viewControllerA *viewA = [[viewControllerA alloc] init]; [self presentModalViewController:viewA animated:YES]; } - (void)display:(NSInteger)myNum { NSLog(@"YES"); [label setText:[NSString stringWithFormat:@"%d", myNum]]; } @end YES is logged successfully, but the label's text does not change. I have made sure that all of my connections in Interface Builder are correct, in fact there are other (IBAction) methods in my program that change the text of this very label, and all of those other methods work perfectly... Any ideas, guys? You don't need to give me a full solution, any bits of information will help. Thanks.

    Read the article

  • How do I ignore an "invalid" SSL certificate in Objective-C?

    - by ipwnstuff
    Currently I have: NSArray* array = [NSArray arrayWithObjects:@"auth.login",@"username",@"password", nil]; NSData* packed_array = [array messagePack]; NSURL* url = [NSURL URLWithString:@"https://192.168.1.149:3790/api/1.0"]; NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url]; [request setHTTPMethod:@"POST"]; [request setValue:@"RPC Server" forHTTPHeaderField:@"Host"]; [request setValue:@"binary/message-pack" forHTTPHeaderField:@"Content-Type"]; [request setValue:[NSString stringWithFormat:@"%d",[packed_array length]] forHTTPHeaderField:@"Content-Length"]; [request setHTTPBody:packed_array]; NSURLResponse *response; NSError *error; responseData = [NSMutableData dataWithData:[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]]; NSLog(@"response data: %@",[responseData messagePackParse]); NSLog(@"error: %@",error); - (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace { NSLog(@"called canAuthenticateAgainstProtectionSpace"); return [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]; } - (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge { NSLog(@"called didReceiveAuthenticationChallenge"); [challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge]; } Which returns "Error Domain=NSURLErrorDomain Code=-1202 "The certificate for this server is invalid"…" How should I be implementing the answer from this question?

    Read the article

  • Int Showing as Long Odd Value

    - by Josh Kahane
    Hi I am trying to send an int in my iphone game for game center multiplayer. The integer is coming up and appearing as an odd long integer value rather than the expected one. I have this in my .h: typedef enum { kPacketTypeScore, } EPacketTypes; typedef struct { EPacketTypes type; size_t size; } SPacketInfo; typedef struct { SPacketInfo packetInfo; int score; } SScorePacket; Then .m: Sending data: scoreData *score = [scoreData sharedData]; SScorePacket packet; packet.packetInfo.type = kPacketTypeScore; packet.packetInfo.size = sizeof(SScorePacket); packet.score = score.score; NSData* dataToSend = [NSData dataWithBytes:&packet length:packet.packetInfo.size]; NSError *error; [self.myMatch sendDataToAllPlayers: dataToSend withDataMode: GKMatchSendDataUnreliable error:&error]; if (error != nil) { // handle the error } Receiving: SPacketInfo* packet = (SPacketInfo*)[data bytes]; switch (packet->type) { case kPacketTypeScore: { SScorePacket* scorePacket = (SScorePacket*)packet; scoreData *score = [scoreData sharedData]; [scoreLabel setString:[NSString stringWithFormat:@"You: %d Challenger: %d", score.score, scorePacket]]; break; } default: CCLOG(@"received unknown packet type %i (size: %u)", packet->type, packet->size); break; } Any ideas? Thanks.

    Read the article

  • receiving signal: EXC_BAD_ACCESS in web service call function

    - by murali
    I'm new to iPhone development. I'm using xcode 4.2. When I click on the save button, I'm getting values from the html page and my web service is processing them, and then I get the error: program received signal: EXC_BAD_ACCESS in my web service call function. Here is my code: NSString *val=[WebviewObj stringByEvaluatingJavaScriptFromString:@"save()"]; NSLog(@"return value:: %@",val); [adict setObject:[NSString stringWithFormat:@"%i",userid5] forKey:@"iUser_Id" ]; [adict setObject:[[val componentsSeparatedByString:@","]objectAtIndex:0] forKey:@"vImage_Url"]; [adict setObject:[[val componentsSeparatedByString:@","]objectAtIndex:1] forKey:@"IGenre_Id"]; [adict setObject:[[val componentsSeparatedByString:@","]objectAtIndex:2] forKey:@"vTrack_Name"]; [adict setObject:[[val componentsSeparatedByString:@","]objectAtIndex:3] forKey:@"vAlbum_Name"]; [adict setObject:[[val componentsSeparatedByString:@","]objectAtIndex:4] forKey:@"vMusic_Url"]; [adict setObject:[[val componentsSeparatedByString:@","]objectAtIndex:5] forKey:@"iTrack_Duration_min"]; [adict setObject:[[val componentsSeparatedByString:@","]objectAtIndex:6] forKey:@"iTrack_Duration_sec"]; [adict setObject:[[val componentsSeparatedByString:@","]objectAtIndex:7] forKey:@"vDescription"]; NSLog(@"dict==%@",[adict description]); NSString *URL2= @"http://184.164.156.55/Music/Track.asmx/AddTrack"; obj=[[UrlController alloc]init]; obj.URL=URL2; obj.InputParameters = adict; [obj WebserviceCall]; obj.delegate= self; //this is my function..it is working for so many function calls -(void)WebserviceCall{ webData = [[NSMutableData alloc] init]; NSMutableURLRequest *urlRequest = [[ NSMutableURLRequest alloc ] initWithURL: [ NSURL URLWithString: URL ] ]; NSString *httpBody = @""; for(id key in InputParameters) { if([httpBody length] == 0){ httpBody=[httpBody stringByAppendingFormat:@"&%@=%@",key,[InputParameters valueForKey:key]]; } else{ httpBody=[httpBody stringByAppendingFormat:@"&%@=%@",key,[InputParameters valueForKey:key]]; } } httpBody = [httpBody stringByAppendingFormat:httpBody];//Here i am getting EXC_BAD_ACCESS [urlRequest setHTTPMethod: @"POST" ]; [urlRequest setHTTPBody:[httpBody dataUsingEncoding:NSUTF8StringEncoding]]; [urlRequest setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"content-type"]; NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self]; } Can any one help me please? thanks in advance

    Read the article

  • Custom class deallocated as soon as the app starts.

    - by Tangrs
    Heya, I've added a class object to the nib file. All connections are made. But for some reason, the object is deallocated as soon as it's created. Here's the code: control.h: #import <Foundation/Foundation.h> @interface control : NSObject { IBOutlet UILabel *PlayerScore; } -(IBAction) addPoint: sender; -(void) dealloc; @end control.m: #import "control.h" @implementation control -(IBAction)addPoint: sender { NSLog(@"Ohhai. Didn't crash."); //Doesn't even make it to this stage. int i = [PlayerScore.text intValue]; PlayerScore.text=[NSString stringWithFormat: @"%d",++i]; } -(void) dealloc { NSLog(@"ZOMGWTF?"); [super dealloc]; } @end Here is the console log: [Session started at 2010-06-09 19:47:57 +1000.] 2010-06-09 19:47:58.771 App[91100:207] ZOMGWTF? And after I click the button which messages addPoint, of course, it crashes. 2010-06-09 19:47:59.703 App[91100:207] * -[control] performSelector:withObject:withObject:]: message sent to deallocated instance 0x3843d80 Does anyone have any ideas?

    Read the article

  • Include Multiple Labels and change the value of the same in Iphone, Objective C

    - by user576569
    I m trying to insert label in each row of the cell. Displaying integer. and I m trying to increase the quantity if user click on button add or minus I able to insert button in UITableView Cell as well the function to change the value. But when I click on add button it changes value only for the last row and not on the specific row. //MY code to insert label in each cell txtQty = [[UILabel alloc] initWithFrame:CGRectMake(233,7,20,20)]; txtQty.text = [NSString stringWithFormat:@"%@",[nos objectAtIndex:indexPath.row]]; txtQty.tag = count; txtQty.textColor =[UIColor whiteColor]; txtQty.backgroundColor = [UIColor clearColor]; [cell.contentView addSubview:txtQty]; //Button Creation UIButton *button2 = [[UIButton alloc] initWithFrame:CGRectMake(180,5,30,30)]; [button2 addTarget:self action:@selector(subAddSubQty:) forControlEvents:UIControlEventTouchUpInside]; [button2 setTag:count]; [cell.contentView addSubview:button2]; now what happening is suppose there are 3 rows in table and I click on the 1st row add button the value gets change in the last label i.e at 3rd row and not of the 1st row How to solve these?? please help Thank You

    Read the article

  • Custom Font. Keeping the font width same.

    - by user338322
    I am trying to draw a string using quartz 2d. What i am doing is, i am drawing each letter of the string individually, because each letter has special attributes associated with it, by taking each letter into a new string. The string gets printed, but the space between the letters is not uniform. It looks very ugly to read . I read someting about using custom fonts. But i have no Idea, if I can do it!! my code is here. (void) drawRect : (CGRect)rect{ NSString *string=@"My Name Is Adam"; float j=0; const char *charStr=[string cStringUsingEncoding: NSASCIIStringEncoding]; for(int i=0;i { NSString *str=[NSString stringWithFormat:@"%c",charStr[i]]; const char *s=[str cStringUsingEncoding:NSASCIIStringEncoding]; NSLog(@"%s",s); CGContextRef context=[self getMeContextRef]; CGContextSetTextMatrix (context,CGAffineTransformMakeScale(1.0, -1.0)) ; CGContextSelectFont(context, "Arial", 24, kCGEncodingMacRoman); //CGContextSetCharacterSpacing (context, 10); CGContextSetRGBFillColor (context, 0,0,200, 1); CGContextSetTextDrawingMode(context,kCGTextFill); CGContextShowTextAtPoint(context, 80+j,80,s,1); j=j+15; } } In the output 'My Name is Adam' gets printed but the space between the letters is not uniform.!! is there any way to make the space uniform!!!

    Read the article

  • when i set property(retain), one "self" = one "retain"?

    - by Walter
    although I'm about to finish my first app, I'm still confused about the very basic memory management..I've read through many posts here and apple document, but I'm still puzzled.. For example..I'm currently doing things like this to add a label programmatically: @property (retain, nonatomic) UILabel *showTime; @sythesize showTime; showTime = [[UILabel alloc] initWithFrame:CGRectMake(45, 4, 200, 36)]; [self.showTime setText:[NSString stringWithFormat:@"%d", time]]; [self.showTime setFont:[UIFont fontWithName:@"HelveticaRoundedLT-Bold" size:23]]; [self.showTime setTextColor:numColor]; self.showTime.backgroundColor = [UIColor clearColor]; [self addSubview:self.showTime]; [showTime release]; this is my current practice, for UILabel, UIButton, UIImageView, etc... [Alloc init] it without self., coz I know this will retain twice.. but after the allocation, I put back the "self." to set the attributes.. My gut feel tells me I am doing wrong, but it works superficially and I found no memory leak in analyze and instruments.. can anyone give my advice? when I use "self." to set text and set background color, does it retain one automatically? THX so much!

    Read the article

  • Problem in data binding in NSString?

    - by Rajendra Bhole
    Hi, I selecting the row of the table. The text of the row i stored in the application delegate object as a NSString. That NSString i want to retrieving or binding in SELECT statement of SQLite query, For that i written code in the TableView Class (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { selectedText = [appDelegate.categoryArray objectAtIndex:indexPath.row]; appDelegate.selectedTextOfRow = selectedText; ListOfPrayersViewController *listVC = [[ListOfPrayersViewController alloc] init]; [self.navigationController pushViewController:listVC animated:YES]; [listVC release]; } and database class class code is. + (void) getDuas:(NSString *)dbPath{ if(sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK){ SalahAppDelegate *appDelegate = (SalahAppDelegate *)[[UIApplication sharedApplication] delegate]; NSString *categoryTextForQuery =[NSString stringWithFormat:@"SELECT Category FROM Prayer WHERE Category ='%s'", appDelegate.selectedTextOfRow ]; NSLog(@"The Text %@", categoryTextForQuery); //const char *sqlQuery1 = (char *)categoryTextForQuery; //const char *sqlQuery = "SELECT Category FROM Prayer WHERE Category = 'Invocations for the beginning of the prayer'"; sqlite3_stmt *selectstmt; if(sqlite3_prepare_v2(database, [categoryTextForQuery UTF8String], -1, &selectstmt, NULL) == SQLITE_OK){ appDelegate.duasArray =[[NSMutableArray alloc] init]; while(sqlite3_step(selectstmt) == SQLITE_ROW){ NSString *dua = [[NSString alloc] initWithCString:(char *)sqlite3_column_text(selectstmt,0) encoding:NSASCIIStringEncoding]; Prayer *prayerObj = [[Prayer alloc] initwithDuas:dua]; prayerObj.DuaName = dua; [appDelegate.duasArray addObject:prayerObj]; } } } } The code is comes out of loop on the statement or starting the loop of the while(sqlite3_step(selectstmt) == SQLITE_ROW) Why? How i bind the table selected text in SELECT statement of sqlite?

    Read the article

  • How can I get a default value in some instances but not others?

    - by Connor Wagner
    I am making an iPhone app and want to use an 'if' statement and a boolean to set default values in some instances but not others... is this possible? Are there alternative options if it is not possible? In the MainViewController.m I have: @interface MainViewController (){ BOOL moveOver; } [...] - (void)viewDidLoad { [super viewDidLoad]; _label.text = [NSString stringWithFormat:@"%i", computerSpeed]; } } [...] - (void)flipsideViewControllerDidFinish:(FlipsideViewController *)controller { [self dismissViewControllerAnimated:YES completion:nil]; moveOver = true; } The problem that it is redefined when the ViewDidLoad runs... I need a statement that will not redefine when the ViewDidLoad runs. I have something that I feel like is much closer to working... In the ViewDidLoad I have: if (playToInt != 10 || computerMoveSpeed != 3) { moveOver = TRUE; } which connects to my created method, gameLoop. It has if (moveOver == false) { computerMoveSpeed = 3; playToInt = 10; } I have tried putting the code in the gameLoop into the ViewDidLoad, but it had the same effect. When moveOver was false, the computerMoveSpeed and the playToInt were both seemingly 0. I have two UITextFields and typed 10 and 3 in them... does this not set it to the default? It seems to set the default to 0 for both, how do I change this? THIS IS A DIFFERENT ISSUE THAN THE THREE BOOLEAN VALUES QUESTION

    Read the article

  • How can I discard 2 choices out of 4 from my Array of choice

    - by Umaid
    Actually I have four choice out of which i need to discard to choice on button click like 50/50 , then it will show only 2 choice for user to select out which one is correct and one is wrong -(IBAction)Rebind:(id)sender { if (i == [QuizArray count]) { if([sender tag] == 1) //if([sender tag] == 1) { [self.CorrectArr addObject:@"A"]; //[self.CorrectArr addObject:mydiet.varOpt1]; } else if([sender tag] == 2) { [self.CorrectArr addObject:@"B"]; //[self.CorrectArr addObject:mydiet.varOpt2]; } else if([sender tag] == 3) { [self.CorrectArr addObject:@"C"]; //[self.CorrectArr addObject:mydiet.varOpt3]; } else if([sender tag] == 4) { [self.CorrectArr addObject:@"D"]; //[self.CorrectArr addObject:mydiet.varOpt4]; } Score *myscore = [[Score alloc] initWithNibName:@"Score" bundle:nil]; myscore.SelectedArr = CorrectArr; [self.view addSubview:myscore.view]; } else { NSString *questionstring = [NSString stringWithFormat:[[QuizArray objectAtIndex:i] varQuestion]]; self.myquestion.text = questionstring; [btn1 setTitle:[[AnswerArray objectAtIndex:i] varAnswer] forState:normal]; if([sender tag] == 1) { [self.CorrectArr addObject:@"A"]; //addObject:mydiet.varOpt1]; } else if([sender tag] == 2) { [self.CorrectArr addObject:@"B"]; //addObject:mydiet.varOpt2]; } else if([sender tag] == 3) { [self.CorrectArr addObject:@"C"]; //addObject:mydiet.varOpt3]; } else if([sender tag] == 4) { [self.CorrectArr addObject:@"D"]; //addObject:mydiet.varOpt4]; } } i = i + 1; //} }

    Read the article

  • expected ":" before "]" token + confused by earlier errors, bailing out

    - by Colby Bookout
    Ok so im at my wit's end here. I have tried every imaginable thing to get rid of these errors heres my code: - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { // Navigation logic may go here. Create and push another view controller. /* //<#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:@"<#Nib name#>" bundle:nil]; // ... // Pass the selected object to the new view controller. [self.navigationController pushViewController:detailViewController animated:YES]; [detailViewController release]; */ NSInteger row = [indexPath.row]; if (self.nameExcerptPage == nil) { NameOTWexcerpt *nameExcerptPageDetail = [[nameExcerptPage alloc] initWithNibName:@"NameOTWexcerpt" bundle:nil]; self.nameExcerptPage = nameExcerptPageDetail; [nameExcerptPageDetail release]; nameExcerptPage.title = [NSString stringWithFormat:@"%&", [TheBookNavTabs objectAtIndex:row]]; Rothfuss_ReaderAppDelegate *delegate = [[UIApplication sharedApplication] delegate]; [delegate.SecondTableViewController pushViewController:TheBookNavTabs animated:YES]; } } and the error appears where it says "NSInteger row = [indexPath.row]; please help! thanks!

    Read the article

  • SQLite3 database doesn't actually insert data - iPhone

    - by user334934
    I'm trying to add a new entry into my database, but it's not working. There are no errors thrown, and the code that is supposed to be executed after the insertion runs, meaning there are no errors with the query. But still, nothing is added to the database. I've tried both prepared statements and the simpler sqlite3_exec and it's the same result. I know my database is being loaded because the info for the tableview (and subsequent tableviews) are loaded from the database. The connection isn't the problem. Also, the log of the sqlite3_last_insert_rowid(db) returns the correct number for the next row. But still, the information is not saved. Here's my code: db = [Database openDatabase]; NSString *query = [NSString stringWithFormat:@"INSERT INTO lists (name) VALUES('%@')", newField.text]; NSLog(@"Query: %@",query); sqlite3_stmt *statement; if (sqlite3_prepare_v2(db, [query UTF8String], -1, &statement, nil) == SQLITE_OK) { if(sqlite3_step(statement) == SQLITE_DONE){ NSLog(@"You created a new list!"); int newListId = sqlite3_last_insert_rowid(db); MyList *newList = [[MyList alloc] initWithName:newField.text idNumber:[NSNumber numberWithInt:newListId]]; [self.listArray addObject:newList]; [newList release]; [self.tableView reloadData]; sqlite3_finalize(statement); } else { NSAssert1(0, @"Error while inserting data. '%s'", sqlite3_errmsg(db)); } } [Database closeDatabase:db]; Again, no errors have been thrown. The prepare and step statements return SQLITE_OK and SQLITE_DONE respectively, yet nothing happens. Any help is appreciated!

    Read the article

  • NSTimer won't stop it only resets when invalidated & released

    - by J Fries
    When I press my stop button to stop the timer it just resets to the original time and begins counting down again. I have looked everywhere and all I have found is "invalidate" and it isn't working. I want the time to stop when I hit stop and the label to display the original time. I also turned off automatic counting so I could try releasing and it is giving me an error: 0x10e20a5: movl 16(%edx), %edx EXC_BAD_ACCESS (code=2, address=0x10) `NSTimer *rockettTimer; int rocketCount; @interface FirstViewController () @property (strong, nonatomic) IBOutlet UILabel *rocketTimer; - (IBAction)stopButton:(id)sender; - (IBAction)startButton:(id)sender; @end @implementation FirstViewController @synthesize rocketTimer; -(void) rocketTimerRun{ rocketCount = rocketCount - 1; int minuts = rocketCount / 60; int seconds = rocketCount - (minuts * 60); NSString *timerOutput = [NSString stringWithFormat:@"%d:%.2d", minuts, seconds]; rocketTimer.text = timerOutput; } - (IBAction)startButton:(id)sender { rocketCount = 180; rockettTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(rocketTimerRun) userInfo:nil repeats:YES]; - (IBAction)stopButton:(id)sender { [rockettTimer invalidate]; //[rockettTimer release]; } - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. } - (void)viewDidUnload { [self setRocketTimer:nil]; [super viewDidUnload]; // Release any retained subviews of the main view. } - (BOOL)shouldAutorotateToInterfaceOrientation: (UIInterfaceOrientation)interfaceOrientation { if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) { return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown); } else { return YES; } } @end`

    Read the article

  • Simple iOS Get Request Not Pulling in Data

    - by user2793987
    I have a very simple get request that doesn't return data on my script. The script is fine when viewed in the web browser but the app does not pull in the data. Any other script works with this code in the app. I'm unsure of what to do because there shouldn't be a reason for this to not work. Please let me know if you need more information. Here's the script: https://shipstudent.com/complaint_desk/similarPosts.php?username=noah //retrieve saved username from user defaults (it's noah) NSUserDefaults *eUser = [NSUserDefaults standardUserDefaults]; savedUser = [eUser objectForKey:@"user"]; NSLog(@"%@",savedUser); in ViewDidLoad: NSString *categoryParam = [NSString stringWithFormat:@"https://shipstudent.com/complaint_desk/similarPosts.php?username=%@", savedUser]; NSURL *url = [NSURL URLWithString:categoryParam]; NSMutableURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLCacheStorageAllowed timeoutInterval:30.0]; NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self]; if (connection==nil) { NSLog(@"Invalid request"); } -(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { postData = [[NSMutableData alloc]init]; NSLog(@"Response received"); } -(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { [postData appendData:data]; NSLog(@"Data received"); } -(void)connectionDidFinishLoading:(NSURLConnection *)connection { [UIApplication sharedApplication].networkActivityIndicatorVisible = NO; similarPosts = [NSJSONSerialization JSONObjectWithData:postData options:kNilOptions error:nil]; [postsTbl reloadData]; for (id postObject in similarPosts) { NSLog(@"Relatable Post: %@",postObject); } }

    Read the article

< Previous Page | 17 18 19 20 21 22 23 24 25  | Next Page >