Search Results

Search found 103 results on 5 pages for 'nsmutablestring'.

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

  • NSData in CoreData is not saving properly

    - by abisson
    I am currently trying to store images I download from the web into an NSManagedObject class so that I don't have to redownload it every single time the application is opened. I currently have these two classes. Plant.h @property (nonatomic, retain) NSString * name; @property (nonatomic, retain) PlantPicture *picture; PlantPicture.h @property (nonatomic, retain) NSString * bucketName; @property (nonatomic, retain) NSString * creationDate; @property (nonatomic, retain) NSData * pictureData; @property (nonatomic, retain) NSString * slug; @property (nonatomic, retain) NSString * urlWithBucket; Now I do the following: - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath { PlantCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath]; Plant *plant = [self.fetchedResultsController objectAtIndexPath:indexPath]; cell.plantLabel.text = plant.name; if(plant.picture.pictureData == nil) { NSLog(@"Downloading"); NSMutableString *pictureUrl = [[NSMutableString alloc]initWithString:amazonS3BaseURL]; [pictureUrl appendString:plant.picture.urlWithBucket]; NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:pictureUrl]]; AFImageRequestOperation *imageOperation = [AFImageRequestOperation imageRequestOperationWithRequest:request success:^(UIImage *image) { cell.plantImageView.image = image; plant.picture.pictureData = [[NSData alloc]initWithData:UIImageJPEGRepresentation(image, 1.0)]; NSError *error = nil; if (![_managedObjectContext save:&error]) { NSLog(@"Unresolved error %@, %@", error, [error userInfo]); } }]; [imageOperation start]; } else { NSLog(@"Already"); cell.plantImageView.image = [UIImage imageWithData:plant.picture.pictureData]; } NSLog(@"%@", plant.name); return cell; } The plant information is present, as well as the picture object. However, the NSData itself is NEVER saved throughout the application opening and closing. I always have to REDOWNLOAD the image! Any ideas!? [Very new to CoreData... sorry if it is easy!] thanks!

    Read the article

  • How i finding Internate network error using Try..........Catch in iphone?

    - by Rajendra Bhole
    Hi, I developing an application in which i calling web services on iphone. I want to implement Try.......Catch in that code for catching internet and GPRS connection error.The code is as follow, NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease]; [request setURL:[NSURL URLWithString:mainURL5]]; [request setHTTPMethod:@"POST"]; NSHTTPURLResponse* urlResponse = nil; NSError *error = [[[NSError alloc] init] autorelease]; NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error]; result5 = [[NSMutableString alloc] initWithData:responseData encoding:NSUTF8StringEncoding]; I was using Try......catch but it didn't work that code as follows, @try { //prepar request NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease]; [request setURL:[NSURL URLWithString:mainURL5]]; [request setHTTPMethod:@"POST"]; NSHTTPURLResponse* urlResponse = nil; NSError *error = [[[NSError alloc] init] autorelease]; NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error]; result5 = [[NSMutableString alloc] initWithData:responseData encoding:NSUTF8StringEncoding]; } @catch(NSException * e) { [clsMessageBox ShowMessageOK:@"some text" :[e reason]]; }

    Read the article

  • Objective-C Result from a Static Method saved to class instance variable giving "EXC_BAD_ACCESS" when used.

    - by KinGBin
    I am trying to store the md5 string as a class instance variable instead of the actual password. I have a static function that will return a md5 string which I'm trying to store in an instance variable instead of the actual password. I have the following setter for my class instance variable: -(void)setPassword:(NSString *)newpass{ if(newpass != password){ password = [utils md5HexDigest:newpass]; } } This will pass back the correct md5 string and save it to the password variable in my init function: [self setPassword:pword];. If I call another instance method and try to access self.password" I will get "EXC_BAD_ACCESS". I understand that the memory is getting released, but I have no clue to make sure it stays. I have tried alloc init with autorelease with no luck. This is the md5HexDigest function getting called during the init (graciously found in another stackoverflow question): + (NSString*)md5HexDigest:(NSString*)input { const char* str = [input UTF8String]; unsigned char result[CC_MD5_DIGEST_LENGTH]; CC_MD5(str, strlen(str), result); NSMutableString *ret = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH*2]; for(int i = 0; i<CC_MD5_DIGEST_LENGTH; i++) { [ret appendFormat:@"%02x",result[i]]; } return ret; } Any help/pointers would be greatly appreciated. I would rather have the md5 string saved in memory than the actual password calling the md5 every time I needed to use the password. Thanks in advance.

    Read the article

  • Text being printed twice in uitableview

    - by user337174
    I have created a uitableview that calculates the distance of a location in the table. I used this code in cell for row at index path. NSString *lat1 = [object valueForKey:@"Lat"]; NSLog(@"Current Spot Latitude:%@",lat1); float lat2 = [lat1 floatValue]; NSLog(@"Current Spot Latitude Float:%g", lat2); NSString *long1 = [object valueForKey:@"Lon"]; 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); //Location of selected spot CLLocation *loc1 = [[CLLocation alloc] initWithLatitude:lat2 longitude:long2]; //Current Location CLLocation *loc2 = [[CLLocation alloc] initWithLatitude:locLat2 longitude:locLong2]; double distance = [loc1 getDistanceFrom: loc2] / 1600; NSMutableString* converted = [NSMutableString stringWithFormat:@"%.1f", distance]; [converted appendString: @" m"]; It works fine apart from a problem i have just discovered where the distance text is duplicated over the top of the detailed text label when you scroll beyond the height of the page. here's a screen shot of what i mean. Any ideas why its doing this?

    Read the article

  • Working with a string as an array of characters

    - by Malfunction
    I'm having some trouble with a string represented as an array of characters. What I'd like to do, as I would do in java, is the following: while (i < chars.length) { char ch = chars[i]; if ((WORD_CHARS.indexOf(ch) >= 0) == punctuation) { String token = buffer.toString(); if (token.length() > 0) { parts.add(token); } buffer = new StringBuffer(); } buffer.append(ch); i++; } What I'm doing is something like this: while(i < strlen(chars)) { char ch = chars[i]; if(([WORD_CHARS rangeOfString:ch] >= 0) == punctuation) { NSString *token = buffer.toString(); if([token length] > 0) { [parts addObject:token]; } buffer = [NSMutableString string]; } [buffer append(ch)]; i++; } I'm not sure how I'm supposed to convert String token = buffer.toString(); to objective c, where buffer is an NSMutableString. Also, how do I check this if condition in objective c? if ((WORD_CHARS.indexOf(ch) >= 0) == punctuation) WORD_CHARS is an NSString. I'm also having trouble with appending ch to buffer. Any help is greatly appreciated.

    Read the article

  • NSXMLParser values not being retained.

    - by user574947
    This is similar to my previous question. I didn't get an answer, maybe by changing the question I might get an answer. Here is my parsing code: -(void) parser:(NSXMLParser *) parser didStartElement:(NSString *) elementName namespaceURI:(NSString *) namespaceURI qualifiedName:(NSString *) qName attributes:(NSDictionary *) attributeDict { if ([elementName isEqualToString:kimgurl] || [elementName isEqualToString:kone_x] || [elementName isEqualToString:kone_y] || [elementName isEqualToString:kone_radius] || [elementName isEqualToString:ktwo_x] || [elementName isEqualToString:ktwo_y] || [elementName isEqualToString:ktwo_radius]) { elementFound = YES; theItems = [[Items alloc] init]; } } - (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName { if([elementName isEqualToString:kimgurl]) { theItems.imageURL = self.currentValue; [self.currentValue setString:@""]; } else if([elementName isEqualToString:kone_x]) { theItems.iOne_X = self.currentValue; [self.currentValue setString:@""]; } else if([elementName isEqualToString:kone_y]) { theItems.iOne_Y = self.currentValue; [self.currentValue setString:@""]; } else if([elementName isEqualToString:kone_radius]) { theItems.iOne_Radius = self.currentValue; [self.currentValue setString:@""]; } else if([elementName isEqualToString:ktwo_x]) { theItems.iTwo_X = self.currentValue; [self.currentValue setString:@""]; } else if([elementName isEqualToString:ktwo_y]) { theItems.iTwo_Y = self.currentValue; [self.currentValue setString:@""]; } else if([elementName isEqualToString:ktwo_radius]) { theItems.iTwo_Radius = self.currentValue; [self.currentValue setString:@""]; } } -(void) parserDidEndDocument:(NSXMLParser *)parser { NSLog(@"enddocument: %@", theItems.imageURL); } -(void)parser:(NSXMLParser *) parser foundCharacters:(NSString *)string { if (elementFound == YES) { if(!currentValue) { currentValue = [NSMutableString string]; } [currentValue appendString: string]; } } When I get to parserDidEndDocument. The theItems class is empty. Here is Items.h #import <Foundation/Foundation.h> @interface Items : NSObject { @private //parsed data NSString *imageURL; NSString *iOne_X; NSString *iOne_Y; NSString *iOne_Radius; NSString *iTwo_X; NSString *iTwo_Y; NSString *iTwo_Radius; } @property (nonatomic, retain) NSString *imageURL; @property (nonatomic, retain) NSString *iOne_X; @property (nonatomic, retain) NSString *iOne_Y; @property (nonatomic, retain) NSString *iOne_Radius; @property (nonatomic, retain) NSString *iTwo_X; @property (nonatomic, retain) NSString *iTwo_Y; @property (nonatomic, retain) NSString *iTwo_Radius; @end here is Items.m #import "Items.h" @implementation Items @synthesize imageURL; @synthesize iOne_X; @synthesize iOne_Y; @synthesize iOne_Radius; @synthesize iTwo_X; @synthesize iTwo_Y; @synthesize iTwo_Radius; -(void)dealloc { [imageURL release]; [iOne_X release]; [iOne_Y release]; [iOne_Radius release]; [iTwo_X release]; [iTwo_Y release]; [iTwo_Radius release]; [super dealloc]; } @end here is my RootViewController.h #import <UIKit/UIKit.h> @class Items; @interface RootViewController : UIViewController <NSXMLParserDelegate> { NSMutableData *downloadData; NSURLConnection *connection; BOOL elementFound; NSMutableString *currentValue; NSMutableDictionary *pictures; //---xml parsing--- NSXMLParser *xmlParser; Items *theItems; NSMutableArray *aItems; } @property (nonatomic, retain) Items *theItems; @property (nonatomic, retain) NSMutableArray *aItems; @property (nonatomic, retain) NSMutableString *currentValue; @property (nonatomic, retain) NSMutableData *downloadData; @property (nonatomic, retain) NSURLConnection *connection; @end xml file example <?xml version="1.0" encoding="utf-8"?> <data> <test> <url>url</url> <one_x>83</one_x> <one_y>187</one_y> <one_radius>80</one_radius> <two_x>183</two_x> <two_y>193</two_y> <two_radius>76</two_radius> </test> </data>

    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

  • NSXMLParser Memory Allocation Efficiency for the iPhone

    - by Staros
    Hello, I've recently been playing with code for an iPhone app to parse XML. Sticking to Cocoa, I decided to go with the NSXMLParser class. The app will be responsible for parsing 10,000+ "computers", all which contain 6 other strings of information. For my test, I've verified that the XML is around 900k-1MB in size. My data model is to keep each computer in an NSDictionary hashed by a unique identifier. Each computer is also represented by a NSDictionary with the information. So at the end of the day, I end up with a NSDictionary containing 10k other NSDictionaries. The problem I'm running into isn't about leaking memory or efficient data structure storage. When my parser is done, the total amount of allocated objects only does go up by about 1MB. The problem is that while the NSXMLParser is running, my object allocation is jumping up as much as 13MB. I could understand 2 (one for the object I'm creating and one for the raw NSData) plus a little room to work, but 13 seems a bit high. I can't imaging that NSXMLParser is that inefficient. Thoughts? Code... The code to start parsing... NSXMLParser *parser = [[NSXMLParser alloc] initWithData: data]; [parser setDelegate:dictParser]; [parser parse]; output = [[dictParser returnDictionary] retain]; [parser release]; [dictParser release]; And the parser's delegate code... -(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict { if(mutableString) { [mutableString release]; mutableString = nil; } mutableString = [[NSMutableString alloc] init]; } -(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string { if(self.mutableString) { [self.mutableString appendString:string]; } } -(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName { if([elementName isEqualToString:@"size"]){ //The initial key, tells me how many computers returnDictionary = [[NSMutableDictionary alloc] initWithCapacity:[mutableString intValue]]; } if([elementName isEqualToString:hashBy]){ //The unique identifier if(mutableDictionary){ [mutableDictionary release]; mutableDictionary = nil; } mutableDictionary = [[NSMutableDictionary alloc] initWithCapacity:6]; [returnDictionary setObject:[NSDictionary dictionaryWithDictionary:mutableDictionary] forKey:[NSMutableString stringWithString:mutableString]]; } if([fields containsObject:elementName]){ //Any of the elements from a single computer that I am looking for [mutableDictionary setObject:mutableString forKey:elementName]; } } Everything initialized and released correctly. Again, I'm not getting errors or leaking. Just inefficient. Thanks for any thoughts!

    Read the article

  • Updating a deallocated UIWebView from a background thread

    - by Dan Ray
    As you can see from the title, I've programmed myself into a corner and I've got several things working against me... In a UIViewController subclass that manages a large and complex view. One part of it is a UIWebView that contains output from a web request that I had to build and execute, and manually assemble HTML from. Since it takes a second or two to run, I dropped it into the background by calling self performSelectorInBackground:. Then from that method I call there, I use self performSelectorOnMainThread: to get back to the surface of the thread stack to update the UIWebView with what I just got. Like this (which I've cut down to show only the relevant issues): -(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation { //then get mapquest directions NSLog(@"Got called to handle new location!"); [manager stopUpdatingLocation]; [self performSelectorInBackground:@selector(getDirectionsFromHere:) withObject:newLocation]; } - (void)getDirectionsFromHere:(CLLocation *)newLocation { NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; CLLocationCoordinate2D here = newLocation.coordinate; // assemble a call to the MapQuest directions API in NSString *dirURL // ...cut for brevity NSLog(@"Query is %@", dirURL); NSString *response = [NSString stringWithContentsOfURL:[NSURL URLWithString:dirURL] encoding:NSUTF8StringEncoding error:NULL]; NSMutableString *directionsOutput = [[NSMutableString alloc] init]; // assemble response into an HTML table in NSString *directionsOutput // ...cut for brevity [self performSelectorOnMainThread:@selector(updateDirectionsWithHtml:) withObject:directionsOutput waitUntilDone:NO]; [directionsOutput release]; [pool drain]; [pool release]; } - (void)updateDirectionsWithHtml:(NSString *)directionsOutput { [self.directionsWebView loadHTMLString:directionsOutput baseURL:nil]; } This all works totally great, UNLESS I've backed out of this view controller before CLLocationManager hits its delegate method. If this happens after I've already left this view, I get: 2010-06-07 16:38:08.508 EverWondr[180:760b] bool _WebTryThreadLock(bool), 0x1b6830: Tried to obtain the web lock from a thread other than the main thread or the web thread. This may be a result of calling to UIKit from a secondary thread. Crashing now... Despite what this says, I can repeatably cause this crash when I back out too early. I'm not at all convinced that attempting a UI update from a background thread is really the issue; I think it's that my UIWebView is deallocated. I suspect that the fact I was just IN a background thread makes the runtime suspect something's up about that, but I feel fairly sure that's not it. So how do I tell CLLocationManager not to worry about it, when I'm backing out of that view? I tried [self.locationManager stopUpdatingLocation] inside my viewWillDisappear method, but that didn't do it. (Incidentally, MapQuest's apis are FANTASTIC. Way WAY better than anything Google provides. I can't recommend them highly enough.)

    Read the article

  • iPhone - database reading method and memory leaks

    - by Do8821
    Hi, in my application, a RSS reader, I get memory leaks that I can't fix because I can't understand from where they come from. Here is the code pointed out by Instruments. -(void) readArticlesFromDatabase { [self setDatabaseInfo]; sqlite3 *database; articles = [[NSMutableArray alloc] init]; if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) { const char *sqlStatement = "select * from articles"; if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) { while(sqlite3_step(compiledStatement) == SQLITE_ROW) { NSString *aName = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 1)]; NSString *aDate = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 2)]; NSString *aUrl = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 3)]; NSString *aCategory = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 4)]; NSString *aAuthor = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 5)]; NSString *aSummary = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 6)]; NSMutableString *aContent = [NSMutableString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 7)]; NSString *aNbrComments = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 8)]; NSString *aCommentsLink = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 9)]; NSString *aPermalink = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 11)]; [aContent replaceCharactersInRange: [aContent rangeOfString: @"http://www.mywebsite.com/img/action-on.gif"] withString: @"hellocoton-action-on.gif"]; [aContent replaceCharactersInRange: [aContent rangeOfString: @"hhttp://www.mywebsite.com/img/action-on-h.gif"] withString: @"hellocoton-action-on-h.gif"]; [aContent replaceCharactersInRange: [aContent rangeOfString: @"hthttp://www.mywebsite.com/img/hellocoton.gif"] withString: @"hellocoton-hellocoton.gif"]; NSString *imageURLBrut = [self parseArticleForImages:aContent]; NSString *imageURLCache = [imageURLBrut stringByReplacingOccurrencesOfString:@":" withString:@"_"]; imageURLCache = [imageURLCache stringByReplacingOccurrencesOfString:@"/" withString:@"_"]; imageURLCache = [imageURLCache stringByReplacingOccurrencesOfString:@" " withString:@"_"]; NSString *uniquePath = [tmp stringByAppendingPathComponent: imageURLCache]; if([[NSFileManager defaultManager] fileExistsAtPath: uniquePath]) { imageURLCache = [@"../tmp/" stringByAppendingString: imageURLCache]; [aContent replaceCharactersInRange: [aContent rangeOfString: imageURLBrut ] withString: imageURLCache]; } Article *article = [[Article alloc] initWithName:aName date:aDate url:aUrl category:aCategory author:aAuthor summary:aSummary content:aContent commentsNbr:aNbrComments commentsLink:aCommentsLink commentsRSS:@"" enclosure:aPermalink enclosure2:@"" enclosure3:@""]; [articles addObject:article]; article = nil; [article release]; } } sqlite3_finalize(compiledStatement); } sqlite3_close(database); } ` I have a lot of "Article" leaked and NSString matching with these using : [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, X)]; I tried a lot of different code I always have these leaks. Anyone has got an idea to help me?

    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

  • Simple calculator app crashes when a third number key is punched.

    - by Justin
    Hi , I am a newbie to the iphone app world. So I thought I try my luck with a calculator app. Unfortunately I am running into an issue where if I press a third key in the calculator the app crashes. Sometimes I get this error EXC_BAD_ACCESS. Here is a code in my CalculatorViewController.m file. #import "CalculatorViewController.h" @implementation CalculatorViewController @synthesize screenText; - (IBAction)buttonPressed:(id)sender { NSString *title = [sender titleForState:UIControlStateNormal]; [self collect:title]; } - (void)collect:(NSString *)digitz { NSString * newText = nil; if ([digitz isEqualToString:@"+"]) { [self add:result]; big_digit = nil; } else if ([digitz isEqualToString:@"+"]) { [self sub:result]; } else if ([digitz isEqualToString:@"x"]) { [self multiply:result]; } else if ([digitz isEqualToString:@"="]) { [self equate:result]; } else { if (big_digit != nil && [big_digit isEqualToString:@"0"] == FALSE) big_digit = [big_digit stringByAppendingFormat:@"%@",digitz]; else big_digit = (NSMutableString *) digitz; result = (int) big_digit; newText = [[NSString alloc] initWithFormat: @"%@",big_digit]; } screenText.text = newText; [newText release]; } - (void)add:(int)res { NSString * newText = nil; ans = ans + res; newText = [[NSString alloc] initWithFormat: @"%@",ans]; screenText.text = newText; [newText release]; } Can anyone spot an obvious issue here. Here is the respective header file too. #import <UIKit/UIKit.h> @interface CalculatorViewController : UIViewController { UILabel *screenText; int number; int result; int ans; //NSString *big_digit; NSMutableString * big_digit ; } @property (nonatomic, retain) IBOutlet UILabel *screenText; - (IBAction)buttonPressed:(id)sender; - (void)collect:(NSString *)digitz; - (void)add:(int)num; - (void)sub:(int)num; - (void)multiply:(int)num; - (void)equate:(int)num; @end

    Read the article

  • How to put Google adsense in iPhone application?

    - by oksk
    Hi all. I have a question about adsense. I want to put Google adsense in my application to be developed. But after testing my code, It wasn't shown. this is my code self.webView.userInteractionEnabled = NO; NSMutableString *manageableHTML = [[[NSMutableString alloc] init] autorelease]; [manageableHTML appendFormat:@"<html><head></head>"]; [manageableHTML appendFormat:@"<body>"]; [manageableHTML appendFormat:@"<script type=\"text/javascript\"><!--"]; [manageableHTML appendFormat:@"window.googleAfmcRequest = {"]; [manageableHTML appendFormat:@"client: 'ca-mb-pub-7564235160823935',"]; [manageableHTML appendFormat:@"ad_type: 'text_image',"]; [manageableHTML appendFormat:@"output: 'html',"]; [manageableHTML appendFormat:@"channel: '2052458338',"]; [manageableHTML appendFormat:@"format: '320x50_mb',"]; [manageableHTML appendFormat:@"oe: 'utf8',"]; [manageableHTML appendFormat:@"color_border: '336699',"]; [manageableHTML appendFormat:@"color_bg: 'FFFFFF',"]; [manageableHTML appendFormat:@"color_link: '0000FF',"]; [manageableHTML appendFormat:@"color_text: '000000',"]; [manageableHTML appendFormat:@"color_url: '008000',"]; [manageableHTML appendFormat:@"};"]; [manageableHTML appendFormat:@"//--></script>"]; [manageableHTML appendFormat:@"<script type=\"text/javascript\" "]; [manageableHTML appendFormat:@"src=\"http://pagead2.googlesyndication.com/pagead/show_afmc_ads.js\"></script>"]; [manageableHTML appendFormat:@"</body></html>"]; [self.webView loadHTMLString:manageableHTML baseURL:nil]; [self.view addSubview:self.webView]; Bofore testing, this javascript code are well operated in my google blog. I found that this code work at only mobile device. and I checked it through safari of my ipod touch. (It works well.) But Checking in the application, I don't see adsense. what is something wrong?

    Read the article

  • Set text equal to string and pass to receipt printer at a different size on iOS

    - by Max Roper
    I am using the StarIO SDK to print text to a receipt printer and I am trying to get a certain line of text larger than the rest. I have some help from their support but I can't really get it to go. -(void)print{ NSMutableString *final=[NSMutableString stringWithFormat:@"-----"]; [final appendFormat:@"\n\nLevel:%@ Section:%@ Row:%@ Seat:%@", [response_dict objectForKey:@"level"], [response_dict objectForKey:@"section"],[response_dict objectForKey:@"row"],[response_dict objectForKey:@"seat"]]; There is a bunch of other stuff that is printing, but that is the line that I would like to be a different size than the rest. The StarIO support said that I should try and pass that to this... -(IBAction)PrintText { NSString *portName = [IOS_SDKViewController getPortName]; NSString *portSettings = [IOS_SDKViewController getPortSettings]; [PrinterFunctions PrintTextWithPortname:portName portSettings:portSettings heightExpansion:heightExpansion widthExpansion:widthExpansion textData:textData textDataSize:[textNSData length]]; free(textData); } Would love some help if possible. :) Thanks so much. This is the main bit I think I would need from the StarIO Text formatting doc... - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; if (self) { array_hieghtExpansion = [[NSMutableArray alloc] init]; [array_hieghtExpansion addObject:@"1"]; [array_hieghtExpansion addObject:@"2"]; [array_hieghtExpansion addObject:@"3"]; [array_hieghtExpansion addObject:@"4"]; [array_hieghtExpansion addObject:@"5"]; [array_hieghtExpansion addObject:@"6"]; array_widthExpansion = [[NSMutableArray alloc] init]; [array_widthExpansion addObject:@"1"]; [array_widthExpansion addObject:@"2"]; [array_widthExpansion addObject:@"3"]; [array_widthExpansion addObject:@"4"]; [array_widthExpansion addObject:@"5"]; [array_widthExpansion addObject:@"6"]; array_alignment = [[NSMutableArray alloc] init]; [array_alignment addObject:@"Left"]; [array_alignment addObject:@"Center"]; [array_alignment addObject:@"Right"]; } return self; } and int heightExpansion = [pickerpopup_heightExpansion getSelectedIndex]; int widthExpansion = [pickerpopup_widthExpansion getSelectedIndex];

    Read the article

  • How to pass an int value on UIButton click inside UITableView

    - by Toran Billups
    So I have a view controller with a single UITableView that shows a string to the user. But I needed a way to have the user select this object by id using a normal UIButton so I added it as a subview and the click event works as expected. The issue is this - how can I pass an int value to this click event? I've tried using attributes of the button like button.tag or button.accessibilityhint without much success. How do the professionals pass an int value like this? Also it's important that I can get the actual [x intValue] from the int later in the process. A while back I thought I could do this with a simple NSLog(@"the actual selected hat was %d", [obj.idValue intValue]); But this doesn't appear to work (any idea how I can pull the actual int value directly from the variable?). The working code I have is below - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease]; } if ([self.hats count] > 0) { Hat* obj = [self.hats objectAtIndex: [indexPath row]]; NSMutableString* fullName = [[NSMutableString alloc] init]; [fullName appendFormat:@"%@", obj.name]; [fullName appendFormat:@" %@", obj.type]; cell.textLabel.text = fullName; cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton; //add the button to subview hack UIButton* button = [UIButton buttonWithType:UIButtonTypeRoundedRect]; button.frame = CGRectMake(50, 5, 50, 25); [button setTitle:@"Select" forState:UIControlStateNormal]; button.backgroundColor = [UIColor clearColor]; button.adjustsImageWhenHighlighted = YES; button.tag = obj.idValue; //this is my current hack to add the id but no dice :( [button addTarget:self action:@selector(action:) forControlEvents:UIControlEventTouchUpInside]; [cell.contentView addSubview:button]; //hack } return cell; } - (void)action:(id)sender { int* hatId = ((UIButton *)sender).tag; //try to pull the id value I added above ... //do something w/ the hatId }

    Read the article

  • stringByAppendingFormat not working

    - by iFloh
    I have an NSString and fail to apply the following statement: NSString *myString = @"some text"; [myNSString stringByAppendingFormat:@"some text = %d", 3]; no log or error, the string just doesn't get changed. I already tried with NSString (as documented) and NSMutableString. any clues most welcome.

    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

  • Can I change an NSDictionaries key?

    - by Mark Reid
    I have an NSDictionary object that is populated by NSMutableStrings for its keys and objects. I have been able to change the key by changing the original NSMutableString with the setString: method. They key however remains the same regardless of the contents of the string used to set the key initially. My question is, is the key protected from being changed meaning it will always be the same unless I remove it and add another to the dictionary? Thanks.

    Read the article

  • Return NSString from a recursive function

    - by Dave
    Hi, I have a recursive function that is designed to take parse a tree and store all the values of the tree nodes in an NSString. Is the algorithm below correct? NSString* finalString = [self parseTree:rootNode string:@""]; -(NSString*)parseTree:(Node*)currentNode string:(NSMutableString*)myString { [myString appendText:currentNode.value]; for(int i=0;i<[currentNode.children length];i++){ return [self parseTree:[currentNode.children] objectAtIndex:i] string:myString]; } }

    Read the article

  • NSXMLParser & memory leaks

    - by HBR
    Hi, I am parsing an XML file using a custom class that instanciates & uses NSXMLParser. On the first call everything is fine but on the second, third and later calls Instruments show tens of memory leaks on certain lines inside didEndElement, didEndElement and foundCharacters functions. I googled it and found some people having this issue, but I didn't find anything that could really help me. My Parser class looks like this : Parser.h @interface XMLParser : NSObject { NSMutableArray *data; NSMutableString *currentValue; NSArray *xml; NSMutableArray *videos; NSMutableArray *photos; NSXMLParser *parser; NSURLConnection *feedConnection; NSMutableData *downloadedData; Content *content; Video *video; BOOL nowPhoto; BOOL nowVideo; BOOL finished; BOOL webTV; } -(void)parseXML:(NSURL*)xmlURL; -(int)getCount; -(NSArray*)getData; //- (void)handleError:(NSError *)error; //@property(nonatomic, retain) NSMutableString *currentValue; @property(nonatomic, retain) NSURLConnection *feedConnection; @property(nonatomic, retain) NSMutableData *downloadedData; @property(nonatomic, retain) NSArray *xml; @property(nonatomic, retain) NSXMLParser *parser; @property(nonatomic, retain) NSMutableArray *data; @property(nonatomic, retain) NSMutableArray *photos; @property(nonatomic, retain) NSMutableArray *videos; @property(nonatomic, retain) Content *content; @property(nonatomic, retain) Video *video; @property(nonatomic) BOOL finished; @property(nonatomic) BOOL nowPhoto; @property(nonatomic) BOOL nowVideo; @property(nonatomic) BOOL webTV; @end Parser.m #import "Content.h" #import "Video.h" #import "Parser.h" #import <CFNetwork/CFNetwork.h> @implementation XMLParser @synthesize xml, parser, finished, nowPhoto, nowVideo, webTV; @synthesize feedConnection, downloadedData, data, content, photos, videos, video; -(void)parseXML:(NSURL*)xmlURL { /* NSURLRequest *req = [NSURLRequest requestWithURL:xmlURL]; self.feedConnection = [[[NSURLConnection alloc] initWithRequest:req delegate:self] autorelease]; [UIApplication sharedApplication].networkActivityIndicatorVisible = YES; */ [[NSURLCache sharedURLCache] setMemoryCapacity:0]; [[NSURLCache sharedURLCache] setDiskCapacity:0]; NSXMLParser *feedParser = [[NSXMLParser alloc] initWithContentsOfURL:xmlURL]; //NSXMLParser *feedParser = [[NSXMLParser alloc] initWithData:theXML]; [self setParser:feedParser]; [feedParser release]; [[self parser] setDelegate:self]; [[self parser] setShouldResolveExternalEntities:YES]; [[self parser] parse]; } - (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict { if ([elementName isEqualToString:@"articles"]) { self.finished = NO; self.nowPhoto = NO; self.nowVideo = NO; self.webTV = NO; if (!data) { NSMutableArray *tmp = [[NSMutableArray alloc] init]; [self setData:tmp]; [tmp release]; return ; } } if ([elementName isEqualToString:@"WebTV"]) { self.finished = NO; self.nowPhoto = NO; self.nowVideo = NO; self.webTV = YES; if (!data) { NSMutableArray *tmp = [[NSMutableArray alloc] init]; [self setData:tmp]; [tmp release]; return ; } } if ([elementName isEqualToString:@"photos"]) { if (!photos) { NSMutableArray *tmp = [[NSMutableArray alloc] init]; [self setPhotos:tmp]; [tmp release]; return; } } if ([elementName isEqualToString:@"videos"]) { if (!videos) { NSMutableArray *tmp = [[NSMutableArray alloc] init]; [self setVideos:tmp]; [tmp release]; return; } } if ([elementName isEqualToString:@"photo"]) { self.nowPhoto = YES; self.nowVideo = NO; } if ([elementName isEqualToString:@"video"]) { self.nowPhoto = NO; self.nowVideo = YES; } if ([elementName isEqualToString:@"WebTVItem"]) { if (!video) { Video *tmp = [[Video alloc] init]; [self setVideo:tmp]; [tmp release]; } NSString *videoId = [attributeDict objectForKey:@"id"]; [[self video] setVideoId:[videoId intValue]]; } if ([elementName isEqualToString:@"article"]) { if (!content) { Content *tmp = [[Content alloc] init]; [self setContent:tmp]; [tmp release]; } NSString *contentId = [attributeDict objectForKey:@"id"]; [[self content] setContentId:[contentId intValue]]; return; } if ([elementName isEqualToString:@"category"]) { NSString *categoryId = [attributeDict objectForKey:@"id"]; NSString *parentId = [attributeDict objectForKey:@"parent"]; [[self content] setCategoryId:[categoryId intValue]]; [[self content] setParentId:[parentId intValue]]; categoryId = nil; parentId = nil; return; } if ([elementName isEqualToString:@"vCategory"]) { NSString *categoryId = [attributeDict objectForKey:@"id"]; NSString *parentId = [attributeDict objectForKey:@"parent"]; [[self video] setCategoryId:[categoryId intValue]]; [[self video] setParentId:[parentId intValue]]; categoryId = nil; parentId = nil; return; } } - (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string { if (!currentValue) { currentValue = [[NSMutableString alloc] initWithCapacity:1000]; } if (currentValue != @"\n") [currentValue appendString:string]; } - (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName { NSString *cleanValue = [currentValue stringByReplacingOccurrencesOfString:@"\n" withString:@""] ; if ([elementName isEqualToString:@"articles"]) { self.finished = YES; //[content release]; } if ([elementName isEqualToString:@"article"]) { [[self data] addObject:[self content]]; [self setContent:nil]; [self setPhotos:nil]; [self setVideos:nil]; /* [content release]; content = nil; [videos release]; videos = nil; [photos release]; photos = nil; */ } if ([elementName isEqualToString:@"WebTVItem"]) { [[self data] addObject:[self video]]; [self setVideo:nil]; //[video release]; //video = nil; } if ([elementName isEqualToString:@"title"]) { //NSLog(@"Tit: %@",cleanValue); [[self content] setTitle:cleanValue]; } if ([elementName isEqualToString:@"vTitle"]) { [[self video] setTitle:cleanValue]; } if ([elementName isEqualToString:@"link"]) { //NSURL *url = [[NSURL alloc] initWithString:cleanValue] ; [[self content] setUrl:[NSURL URLWithString:cleanValue]]; [[self content] setLink: cleanValue]; //[url release]; //url = nil; } if ([elementName isEqualToString:@"vLink"]) { [[self video] setLink:cleanValue]; [[self video] setUrl:[NSURL URLWithString:cleanValue]]; } if ([elementName isEqualToString:@"teaser"]) { NSString *tmp = [cleanValue stringByReplacingOccurrencesOfString:@"##BREAK##" withString:@"\n"]; [[self content] setTeaser:tmp]; tmp = nil; } if ([elementName isEqualToString:@"content"]) { NSString *tmp = [cleanValue stringByReplacingOccurrencesOfString:@"##BREAK##" withString:@"\n"]; [[self content] setContent:tmp]; tmp = nil; } if ([elementName isEqualToString:@"category"]) { [[self content] setCategory:cleanValue]; } if ([elementName isEqualToString:@"vCategory"]) { [[self video] setCategory:cleanValue]; } if ([elementName isEqualToString:@"date"]) { [[self content] setDate:cleanValue]; } if ([elementName isEqualToString:@"vDate"]) { [[self video] setDate:cleanValue]; } if ([elementName isEqualToString:@"thumbnail"]) { [[self content] setThumbnail:[NSURL URLWithString:cleanValue]]; [[self content] setThumbnailURL:cleanValue]; } if ([elementName isEqualToString:@"vThumbnail"]) { [[self video] setThumbnailURL:cleanValue]; [[self video] setThumbnail:[NSURL URLWithString:cleanValue]]; } if ([elementName isEqualToString:@"vDirectLink"]){ [[self video] setDirectLink: cleanValue]; } if ([elementName isEqualToString:@"preview"]){ [[self video] setPreview: cleanValue]; } if ([elementName isEqualToString:@"thumbnail_position"]){ [[self content] setThumbnailPosition: cleanValue]; } if ([elementName isEqualToString:@"url"]) { if (self.nowPhoto == YES) { [[self photos] addObject:cleanValue]; } else if (self.nowVideo == YES) { [[self videos] addObject:cleanValue]; } } if ([elementName isEqualToString:@"photos"]) { [[self content] setPhotos:[self photos]]; //[photos release]; //photos = nil; self.nowPhoto = NO; } if ([elementName isEqualToString:@"videos"]) { [[self content] setVideos:[self videos]]; //[videos release]; //videos = nil; self.nowVideo = NO; } //[cleanValue release]; //cleanValue = nil; [currentValue release]; currentValue = nil; } - (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError { UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"Error" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil]; [alert show]; [alert release]; } -(NSArray*)getData { return data; } -(int)getCount { return [data count]; } - (void)dealloc { [parser release]; //[data release]; //[photos release]; //[videos release]; //[video release]; //[content release]; [currentValue release]; [super dealloc]; } @end Somewhere in my code, I create an instance of this class : XMLParser* feed = [[XMLParser alloc] init]; [self setRssParser:feed]; [feed release]; // Parse feed NSString *url = [NSString stringWithFormat:@"MyXMLURL"]; [[self rssParser] parseXML:[NSURL URLWithString:url]]; Now the problem is that after the first (which has zero leaks), instruments shows leaks in too many parts like this one (they are too much to enumerate them all, but all the calls look the same, I made the leaking line bold) : in didEndElement : if ([elementName isEqualToString:@"link"]) { // THIS LINE IS LEAKING => INSTRUMENTS SAYS IT IS A NSCFString LEAK [self content] setUrl:[NSURL URLWithString:cleanValue]]; [[self content] setLink: cleanValue]; } Any idea how to fix this pealse ? Could this be the same problem as the one mentioned (as an apple bug) by Lee Amtrong here :http://stackoverflow.com/questions/1598928/nsxmlparser-leaking

    Read the article

  • NSURLSession and amazon S3 uploads

    - by George Green
    I have an app which is currently uploading images to amazon S3. I have been trying to switch it from using NSURLConnection to NSURLSession so that the uploads can continue while the app is in the background! I seem to be hitting a bit of an issue. The NSURLRequest is created and passed to the NSURLSession but amazon sends back a 403 - forbidden response, if I pass the same request to a NSURLConnection it uploads the file perfectly. Here is the code that creates the response: NSString *requestURLString = [NSString stringWithFormat:@"http://%@.%@/%@/%@", BUCKET_NAME, AWS_HOST, DIRECTORY_NAME, filename]; NSURL *requestURL = [NSURL URLWithString:requestURLString]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:requestURL cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:60.0]; // Configure request [request setHTTPMethod:@"PUT"]; [request setValue:[NSString stringWithFormat:@"%@.%@", BUCKET_NAME, AWS_HOST] forHTTPHeaderField:@"Host"]; [request setValue:[self formattedDateString] forHTTPHeaderField:@"Date"]; [request setValue:@"public-read" forHTTPHeaderField:@"x-amz-acl"]; [request setHTTPBody:imageData]; And then this signs the response (I think this came from another SO answer): NSString *contentMd5 = [request valueForHTTPHeaderField:@"Content-MD5"]; NSString *contentType = [request valueForHTTPHeaderField:@"Content-Type"]; NSString *timestamp = [request valueForHTTPHeaderField:@"Date"]; if (nil == contentMd5) contentMd5 = @""; if (nil == contentType) contentType = @""; NSMutableString *canonicalizedAmzHeaders = [NSMutableString string]; NSArray *sortedHeaders = [[[request allHTTPHeaderFields] allKeys] sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)]; for (id key in sortedHeaders) { NSString *keyName = [(NSString *)key lowercaseString]; if ([keyName hasPrefix:@"x-amz-"]){ [canonicalizedAmzHeaders appendFormat:@"%@:%@\n", keyName, [request valueForHTTPHeaderField:(NSString *)key]]; } } NSString *bucket = @""; NSString *path = request.URL.path; NSString *query = request.URL.query; NSString *host = [request valueForHTTPHeaderField:@"Host"]; if (![host isEqualToString:@"s3.amazonaws.com"]) { bucket = [host substringToIndex:[host rangeOfString:@".s3.amazonaws.com"].location]; } NSString* canonicalizedResource; if (nil == path || path.length < 1) { if ( nil == bucket || bucket.length < 1 ) { canonicalizedResource = @"/"; } else { canonicalizedResource = [NSString stringWithFormat:@"/%@/", bucket]; } } else { canonicalizedResource = [NSString stringWithFormat:@"/%@%@", bucket, path]; } if (query != nil && [query length] > 0) { canonicalizedResource = [canonicalizedResource stringByAppendingFormat:@"?%@", query]; } NSString* stringToSign = [NSString stringWithFormat:@"%@\n%@\n%@\n%@\n%@%@", [request HTTPMethod], contentMd5, contentType, timestamp, canonicalizedAmzHeaders, canonicalizedResource]; NSString *signature = [self signatureForString:stringToSign]; [request setValue:[NSString stringWithFormat:@"AWS %@:%@", self.S3AccessKey, signature] forHTTPHeaderField:@"Authorization"]; Then if I use this line of code: [NSURLConnection connectionWithRequest:request delegate:self]; It works and uploads the file, but if I use: NSURLSessionUploadTask *task = [self.session uploadTaskWithRequest:request fromFile:[NSURL fileURLWithPath:filePath]]; [task resume]; I get the forbidden error..!? Has anyone tried uploading to S3 with this and hit similar issues? I wonder if it is to do with the way the session pauses and resumes uploads, or it is doing something funny to the request..? One possible solution would be to upload the file to an interim server that I control and have that forward it to S3 when it is complete... but this is clearly not an ideal solution! Any help is much appreciated!! Thanks!

    Read the article

  • Resolving html entities with NSXMLParse on iPhone

    - by Roberto
    Hi all, i think i read every single web page relating to this problem but i still cannot find a solution to it, so here i am. I have an HTML web page wich is not under my control and i need to parse it from my iPhone application. Here it is a sample of the web page i'm talking about: <HTML> <HEAD> <META http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> </HEAD> <BODY> <LI class="bye bye" rel="hello 1"> <H5 class="onlytext"> <A name="morning_part">morning</A> </H5> <DIV class="mydiv"> <SPAN class="myclass">something about you</SPAN> <SPAN class="anotherclass"> <A href="http://www.google.it">Bye Bye &egrave; un saluto</A> </SPAN> </DIV> </LI> </BODY> </HTML> I'm using NSXMLParser and it is going well till it find the è html entity. It calls foundCharacters: for "Bye Bye" and then it calls resolveExternalEntityName:systemID:: with an entityName of "egrave". In this method i'm just returning the character "è" trasformed in an NSData, the foundCharacters is called again adding the string "è" to the previous one "Bye Bye " and then the parser raise the NSXMLParserUndeclaredEntityError error. I have no DTD and i cannot change the html file i'm parsing. Do you have any ideas on this problem? Thanks in advance to all of you, Rob. Update (12/03/2010). After the suggestion of Griffo i ended up with something like this: data = [self replaceHtmlEntities:data]; NSXMLParser *parser = [[NSXMLParser alloc] initWithData:data]; [parser setDelegate:self]; [parser parse]; where replaceHtmlEntities:(NSData *) is something like this: - (NSData *)replaceHtmlEntities:(NSData *)data { NSString *htmlCode = [[NSString alloc] initWithData:data encoding:NSISOLatin1StringEncoding]; NSMutableString *temp = [NSMutableString stringWithString:htmlCode]; [temp replaceOccurrencesOfString:@"&amp;" withString:@"&" options:NSLiteralSearch range:NSMakeRange(0, [temp length])]; [temp replaceOccurrencesOfString:@"&nbsp;" withString:@" " options:NSLiteralSearch range:NSMakeRange(0, [temp length])]; ... [temp replaceOccurrencesOfString:@"&Agrave;" withString:@"À" options:NSLiteralSearch range:NSMakeRange(0, [temp length])]; NSData *finalData = [temp dataUsingEncoding:NSISOLatin1StringEncoding]; return finalData; } But i am still looking the best way to solve this problem. I will try TouchXml in the next days but i still think that there should be a way to do this using NSXMLParser API, so if you know how, feel free to write it here :)

    Read the article

  • iPhone Serialization problem

    - by Jenicek
    Hi, I need to save my own created class to file, I found on the internet, that good approach is to use NSKeyedArchiver and NSKeyedUnarchiver My class definition looks like this: @interface Game : NSObject <NSCoding> { NSMutableString *strCompleteWord; NSMutableString *strWordToGuess; NSMutableArray *arGuessedLetters; //This array stores characters NSMutableArray *arGuessedLettersPos; //This array stores CGRects NSInteger iScore; NSInteger iLives; NSInteger iRocksFallen; BOOL bGameCompleted; BOOL bGameOver; } I've implemented methods initWithCoder: and encodeWithCoder: this way: - (id)initWithCoder:(NSCoder *)coder { if([coder allowsKeyedCoding]) { strCompleteWord = [[coder decodeObjectForKey:@"CompletedWord"] copy]; strWordToGuess = [[coder decodeObjectForKey:@"WordToGuess"] copy]; arGuessedLetters = [[coder decodeObjectForKey:@"GuessedLetters"] retain]; // arGuessedLettersPos = [[coder decodeObjectForKey:@"GuessedLettersPos"] retain]; iScore = [coder decodeIntegerForKey:@"Score"]; iLives = [coder decodeIntegerForKey:@"Lives"]; iRocksFallen = [coder decodeIntegerForKey:@"RocksFallen"]; bGameCompleted = [coder decodeBoolForKey:@"GameCompleted"]; bGameOver = [coder decodeBoolForKey:@"GameOver"]; } else { strCompleteWord = [[coder decodeObject] retain]; strWordToGuess = [[coder decodeObject] retain]; arGuessedLetters = [[coder decodeObject] retain]; // arGuessedLettersPos = [[coder decodeObject] retain]; [coder decodeValueOfObjCType:@encode(NSInteger) at:&iScore]; [coder decodeValueOfObjCType:@encode(NSInteger) at:&iLives]; [coder decodeValueOfObjCType:@encode(NSInteger) at:&iRocksFallen]; [coder decodeValueOfObjCType:@encode(BOOL) at:&bGameCompleted]; [coder decodeValueOfObjCType:@encode(BOOL) at:&bGameOver]; } return self; } - (void)encodeWithCoder:(NSCoder *)coder { if([coder allowsKeyedCoding]) { [coder encodeObject:strCompleteWord forKey:@"CompleteWord"]; [coder encodeObject:strWordToGuess forKey:@"WordToGuess"]; [coder encodeObject:arGuessedLetters forKey:@"GuessedLetters"]; //[coder encodeObject:arGuessedLettersPos forKey:@"GuessedLettersPos"]; [coder encodeInteger:iScore forKey:@"Score"]; [coder encodeInteger:iLives forKey:@"Lives"]; [coder encodeInteger:iRocksFallen forKey:@"RocksFallen"]; [coder encodeBool:bGameCompleted forKey:@"GameCompleted"]; [coder encodeBool:bGameOver forKey:@"GameOver"]; } else { [coder encodeObject:strCompleteWord]; [coder encodeObject:strWordToGuess]; [coder encodeObject:arGuessedLetters]; //[coder encodeObject:arGuessedLettersPos]; [coder encodeValueOfObjCType:@encode(NSInteger) at:&iScore]; [coder encodeValueOfObjCType:@encode(NSInteger) at:&iLives]; [coder encodeValueOfObjCType:@encode(NSInteger) at:&iRocksFallen]; [coder encodeValueOfObjCType:@encode(BOOL) at:&bGameCompleted]; [coder encodeValueOfObjCType:@encode(BOOL) at:&bGameOver]; } } And I use these methods to archive and unarchive data: [NSKeyedArchiver archiveRootObject:currentGame toFile:strPath]; Game *currentGame = [NSKeyedUnarchiver unarchiveObjectWithFile:strPath]; I have two problems. 1) As you can see, lines with arGuessedLettersPos is commented, it's because every time I try to encode this array, error comes up(this archiver cannot encode structs), and this array is used for storing CGRect structs. I've seen solution on the internet. The thing is, that every CGRect in the array is converted to an NSString (using NSStringFromCGRect()) and then saved. Is it a good approach? 2)This is bigger problem for me. Even if I comment this line and then run the code successfully, then save(archive) the data and then try to load (unarchive) them, no data is loaded. There aren't any error but currentGame object does not have data that should be loaded. Could you please give me some advice? This is first time I'm using archivers and unarchivers. Thanks a lot for every reply.

    Read the article

  • EXC_BAD_ACCESS in CFAttributedStringSetAttribute and NSNumber?

    - by RichardR
    Hi all, I am getting an infuriating EXC_BAD_ACCESS error in an objective c app I am working on. Any help you could offer would be much appreciated. I have tried the normal debug methods for this error (turning on NSZombieEnabled, checking retain/release/autorelease to make sure I'm not trying to access a deallocated object, etc.) and it hasn't seemed to help. Basically, the error always occurs in this function: ` void op_TJ(CGPDFScannerRef scanner, void *info) { PDFPage *self = info; CGPDFArrayRef array; NSMutableString *tempString = [NSMutableString stringWithCapacity:1]; NSMutableArray *kernArray = [[NSMutableArray alloc] initWithCapacity:1]; if(!CGPDFScannerPopArray(scanner, &array)) { [kernArray release]; return; } for(size_t n = 0; n < CGPDFArrayGetCount(array); n += 2) { if(n >= CGPDFArrayGetCount(array)) continue; CGPDFStringRef pdfString; // if we get a PDF string if (CGPDFArrayGetString(array, n, &pdfString)) { //get the actual string const unsigned char *charstring = CGPDFStringGetBytePtr(pdfString); //add this string to our temp string [tempString appendString:[NSString stringWithCString:(const char*)charstring encoding:[self pageEncoding]]]; //NSLog(@"string: %@", tempString); //get the space after this string CGPDFReal r = 0; if (n+1 < CGPDFArrayGetCount(array)) { CGPDFArrayGetNumber(array, n+1, &r); // multiply by the font size CGFloat k = r; k = -k/1000 * self.tmatrix.a * self.fontSize; CGFloat kKern = self.kern * self.tmatrix.a; k = k + kKern; // add the location and kern to the array NSNumber *tempKern = [NSNumber numberWithFloat:k]; NSLog(@"tempKern address: %p", tempKern); [kernArray addObject:[NSArray arrayWithObjects:[NSNumber numberWithInt:[tempString length] - 1], tempKern, nil]]; } } } // create an attribute string CFMutableAttributedStringRef attString = CFAttributedStringCreateMutable(kCFAllocatorDefault, 10); CFAttributedStringReplaceString(attString, CFRangeMake(0, 0), (CFStringRef)tempString); //apply overall kerning NSNumber *tkern = [NSNumber numberWithFloat:self.kern * self.tmatrix.a * self.fontSize]; CFAttributedStringSetAttribute(attString, CFRangeMake(0, CFAttributedStringGetLength(attString)), kCTKernAttributeName, (CFNumberRef)tkern); //apply individual kern attributes for (NSArray *kernLoc in kernArray) { NSLog(@"kern location: %i, %i", [[kernLoc objectAtIndex:0] intValue],[[kernLoc objectAtIndex:1] floatValue]); CFAttributedStringSetAttribute(attString, CFRangeMake([[kernLoc objectAtIndex:0] intValue], 1), kCTKernAttributeName, (CFNumberRef)[kernLoc objectAtIndex:1]); } CFAttributedStringReplaceAttributedString([self cfAttString], CFRangeMake(CFAttributedStringGetLength([self cfAttString]), 0), attString); //release CFRelease(attString); [kernArray release]; } ` The program always crashes because of line CFAttributedStringSetAttribute(attString, CFRangeMake([[kernLoc objectAtIndex:0] intValue], 1), kCTKernAttributeName, (CFNumberRef)[kernLoc objectAtIndex:1]) And it seems to depend on a few things: if [kernLoc objectAtIndex:1] refers to an [NSNumber numberWithFloat:k] where k = 0 (in other words, if k = 0 above where I populate kernArray) then the program crashes almost immediately If I comment out the line k = k + kKern, it takes longer for the program to crash, but does eventually (why would the crash depend on this value?) If I change the length of CFRangeMake from 1 to 0, it takes a lot longer for the program to crash, but still eventually does. (I don't think I am trying to access beyond the bounds of attString, but am I missing something?) When it crashes, I get something similar to: #0 0x942c7ed7 in objc_msgSend () #1 0x00000013 in ?? () #2 0x0285b827 in CFAttributedStringSetAttribute () #3 0x0000568f in op_TJ (scanner=0x472a590, info=0x4a32320) at /Users/Richard/Desktop/AppTest/PDFHighlight 2/PDFScannerOperators.m:251 Any ideas? It seems like somewhere along the way I am overwriting memory or trying to access memory that has been changed, but I have no idea. If there's anymore information I can provide, please let me know. Thanks, Richard

    Read the article

  • Cocoa Basic HTTP Authentication : Advice Needed..

    - by Kristiaan
    Hello all, im looking to read the contents of a webpage that is secured with a user name and password. this is a mac OS X application NOT an iphone app so most of the things i have read on here or been suggested to read do not seem to work. Also i am a total beginner with Xcode and Obj C i was told to have a look at a website that provided sample code to http auth however so far i have had little luck in getting this working. below is the main code for the button press in my application, there is also another unit called Base64 below that has some code in i had to change to even get it compiling (no idea if what i changed is correct mind you). NSURL *url = [NSURL URLWithString:@"my URL"]; NSString *userName = @"UN"; NSString *password = @"PW"; NSError *myError = nil; // create a plaintext string in the format username:password NSMutableString *loginString = (NSMutableString*)[@"" stringByAppendingFormat:@"%@:%@", userName, password]; // employ the Base64 encoding above to encode the authentication tokens char *encodedLoginData = [base64 encode:[loginString dataUsingEncoding:NSUTF8StringEncoding]]; // create the contents of the header NSString *authHeader = [@"Basic " stringByAppendingFormat:@"%@", [NSString stringWithCString:encodedLoginData length:strlen(encodedLoginData)]]; //NSString *authHeader = [@"Basic " stringByAppendingFormat:@"%@", loginString];//[NSString stringWithString:loginString length:strlen(loginString)]]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL: url cachePolicy: NSURLRequestReloadIgnoringCacheData timeoutInterval: 3]; // add the header to the request. Here's the $$$!!! [request addValue:authHeader forHTTPHeaderField:@"Authorization"]; // perform the reqeust NSURLResponse *response; NSData *data = [NSURLConnection sendSynchronousRequest: request returningResponse: &response error: &myError]; //*error = myError; // POW, here's the content of the webserver's response. NSString *result = [NSString stringWithCString:[data bytes] length:[data length]]; [myTextView setString:result]; code from the BASE64 file #import "base64.h" static char *alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-"; @implementation Base64 +(char *)encode:(NSData *)plainText { // create an adequately sized buffer for the output. every 3 bytes // become four basically with padding to the next largest integer // divisible by four. char * encodedText = malloc((((([plainText length] % 3) + [plainText length]) / 3) * 4) + 1); char* inputBuffer = malloc([plainText length]); inputBuffer = (char *)[plainText bytes]; int i; int j = 0; // encode, this expands every 3 bytes to 4 for(i = 0; i < [plainText length]; i += 3) { encodedText[j++] = alphabet[(inputBuffer[i] & 0xFC) >> 2]; encodedText[j++] = alphabet[((inputBuffer[i] & 0x03) << 4) | ((inputBuffer[i + 1] & 0xF0) >> 4)]; if(i + 1 >= [plainText length]) // padding encodedText[j++] = '='; else encodedText[j++] = alphabet[((inputBuffer[i + 1] & 0x0F) << 2) | ((inputBuffer[i + 2] & 0xC0) >> 6)]; if(i + 2 >= [plainText length]) // padding encodedText[j++] = '='; else encodedText[j++] = alphabet[inputBuffer[i + 2] & 0x3F]; } // terminate the string encodedText[j] = 0; return encodedText;//outputBuffer; } @end when executing the code it stops on the following line with a EXC_BAD_ACCESS ?!?!? NSString *authHeader = [@"Basic " stringByAppendingFormat:@"%@", [NSString stringWithCString:encodedLoginData length:strlen(encodedLoginData)]]; any help would be appreciated as i am a little clueless on this problem, not being very literate with Cocoa, objective c, xcode is only adding fuel to this fire for me.

    Read the article

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