Search Results

Search found 2356 results on 95 pages for 'nsstring'.

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

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

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

    Read the article

  • Get 1 array from 2 arrays (using RestKit 0.20)

    - by Reez
    I'm using RestKit and was wondering how to combine two array's into one array. I already have the data being pulled in separately from API1 and API2, but I don't know how to combine them into 1 tableView. Each API is pulling in media, and I want the combined tableView to show the most recent media (like any standard timeline does these days). I will post any extra code or help as necessary, thanks so much! Below shows API1 + API2 being pulled in correctly, but not combined into the tableView. Only data from API1 shows in the tableView. ViewController.m @interface StackOverflowViewController () @property (strong, nonatomic) NSArray *hArray; @property (strong, nonatomic) NSArray *springs; @property (strong, nonatomic) RKObjectManager *eObjectManager; @property (strong, nonatomic) NSArray *iArray; @property (strong, nonatomic) NSArray *imagesArray; @property (strong, nonatomic) RKObjectManager *iObjectManager; // Wain @property (strong, nonatomic) NSMutableArray *tableDataList; // Laarme @property (nonatomic, strong) NSMutableArray *contentArray; @property (nonatomic, strong) NSDateFormatter *dateFormatter1; // Dan @property (nonatomic, strong) NSMutableArray *combinedModel; @end @implementation StackOverflowViewController @synthesize tableView = _tableView; @synthesize spring; @synthesize leaf; @synthesize theme; @synthesize hArray; @synthesize springs; @synthesize eObjectManager; @synthesize iArray; @synthesize imagesArray; @synthesize iObjectManager; // Wain @synthesize tableDataList; // Laarme @synthesize contentArray; @synthesize dateFormatter1; // Dan @synthesize combinedModel; - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view. [self configureRestKit]; [self loadMediaDan]; [self sortCombinedModel]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } - (void)configureRestKit { // API1 // initialize AFNetworking HTTPClient NSURL *baseURLE = [NSURL URLWithString:@"https://api.e.com"]; AFHTTPClient *clientE = [[AFHTTPClient alloc] initWithBaseURL:baseURLE]; // initialize RestKit RKObjectManager *eManager = [[RKObjectManager alloc] initWithHTTPClient:clientE]; self.eObjectManager = eManager; // setup object mappings RKObjectMapping *feedMapping = [RKObjectMapping mappingForClass:[Feed class]]; [feedMapping addAttributeMappingsFromArray:@[@"headline", @"premium", @"published", @"description"]]; RKObjectMapping *linksMapping = [RKObjectMapping mappingForClass:[Links class]]; RKObjectMapping *webMapping = [RKObjectMapping mappingForClass:[Web class]]; [webMapping addAttributeMappingsFromArray:@[@"href"]]; RKObjectMapping *mobileMapping = [RKObjectMapping mappingForClass:[Mobile class]]; [mobileMapping addAttributeMappingsFromArray:@[@"href"]]; RKObjectMapping *imagesMapping = [RKObjectMapping mappingForClass:[Images class]]; [imagesMapping addAttributeMappingsFromArray:@[@"height", @"width", @"url"]]; [feedMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:@"links" toKeyPath:@"links" withMapping:linksMapping]]; [feedMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:@"images" toKeyPath:@"images" withMapping:imagesMapping]]; [linksMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:@"web" toKeyPath:@"web" withMapping:webMapping]]; [linksMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:@"mobile" toKeyPath:@"mobile" withMapping:mobileMapping]]; // register mappings with the provider using a response descriptor RKResponseDescriptor *responseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:feedMapping method:RKRequestMethodGET pathPattern:nil keyPath:@"feed" statusCodes:[NSIndexSet indexSetWithIndex:200]]; [self.eObjectManager addResponseDescriptor:responseDescriptor]; // API2 // initialize AFNetworking HTTPClient NSURL *baseURLI = [NSURL URLWithString:@"https://api.i.com"]; AFHTTPClient *clientI = [[AFHTTPClient alloc] initWithBaseURL:baseURLI]; // initialize RestKit RKObjectManager *iManager = [[RKObjectManager alloc] initWithHTTPClient:clientI]; self.iObjectManager = iManager; // setup object mappings RKObjectMapping *dataMapping = [RKObjectMapping mappingForClass:[Data class]]; [dataMapping addAttributeMappingsFromArray:@[@"link", @"created_time"]]; RKObjectMapping *imagesMapping = [RKObjectMapping mappingForClass:[ImagesI class]]; [IMapping addAttributeMappingsFromArray:@[@""]]; RKObjectMapping *standardResolutionMapping = [RKObjectMapping mappingForClass:[StandardResolution class]]; [standardResolutionMapping addAttributeMappingsFromArray:@[@"url", @"width", @"height"]]; RKObjectMapping *captionMapping = [RKObjectMapping mappingForClass:[Caption class]]; [captionMapping addAttributeMappingsFromArray:@[@"text", @"created_time"]]; RKObjectMapping *userMapping = [RKObjectMapping mappingForClass:[User class]]; [userMapping addAttributeMappingsFromArray:@[@"username"]]; [dataMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:@"images" toKeyPath:@"images" withMapping:imagesMapping]]; [imagesMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:@"standard_resolution" toKeyPath:@"standard_resolution" withMapping:standardResolutionMapping]]; [dataMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:@"caption" toKeyPath:@"caption" withMapping:captionMapping]]; [dataMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:@"user" toKeyPath:@"user" withMapping:userMapping]]; // register mappings with the provider using a response descriptor RKResponseDescriptor *responseDescriptor2 = [RKResponseDescriptor responseDescriptorWithMapping:dataMapping method:RKRequestMethodGET pathPattern:nil keyPath:@"data" statusCodes:[NSIndexSet indexSetWithIndex:200]]; [self.iObjectManager addResponseDescriptor:responseDescriptor2]; } - (void)loadMedia { // Laarme contentArray = [[NSMutableArray alloc] init]; [self sortByDates]; // API1 NSString *apikey = @kCLIENTKEY; NSDictionary *queryParams = @{@"apikey" : apikey,}; [self.eObjectManager getObjectsAtPath:[NSString stringWithFormat:@"v1/n/?limit=4&leafs=%@&themes=%@", leafAbbreviation, themeID] // Changed limit to 4 for the time being parameters:queryParams success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) { hArray = mappingResult.array; [self.tableView reloadData]; } failure:^(RKObjectRequestOperation *operation, NSError *error) { NSLog(@"No?: %@", error); }]; // API2 [self.iObjectManager getObjectsAtPath:[NSString stringWithFormat:@"v1/u/2/m/recent/?client_id=e999"] parameters:nil success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) { iArray = mappingResult.array; [self.tableView reloadData]; } failure:^(RKObjectRequestOperation *operation, NSError *error) { NSLog(@"No: %@", error); }]; } // Laarme - (void)sortByDates { NSDateFormatter *dateFormatter2 = [[NSDateFormatter alloc] init]; //Do the dateFormatter settings, you may have to use 2 NSDateFormatters if the format is different for Data & Feed //The initialization of the dateFormatter is done before the block, because its alloc/init take some time, and you may have to declare it with "__block" //Since in your edit you do that and it seems it's the same format, just do @property (nonatomic, strong) NSDateFormatter dateFormatter; NSArray *sortedArray = [contentArray sortedArrayUsingComparator:^NSComparisonResult(id a, id b) { // Added Curly Braces around if else statements and used feedObject NSDate *aDate, *bDate; Feed *feedObject = (Feed *)a; Data *dataObject = (Data *)b; if ([a isKindOfClass:[Feed class]]) { //Feed *feedObject = (Feed *)a; aDate = [dateFormatter1 dateFromString:feedObject.published];} else { //if ([a isKindOfClass:[Data class]]) aDate = [dateFormatter2 dateFromString:dataObject.created_time];} if ([b isKindOfClass:[Feed class]]) { bDate = [dateFormatter1 dateFromString:feedObject.published];} else {//if ([b isKindOfClass:[Data class]]) bDate = [dateFormatter2 dateFromString:dataObject.created_time];} return [aDate compare:bDate]; }]; } #pragma mark - Table View - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return 1; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { // API1 //return hArray.count; // API2 //return iArray.count; // API1 + API2 return hArray.count + iArray.count; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { UITableViewCell *cell; if(indexPath.row < hArray.count) { // Date Change NSDateFormatter *df = [[NSDateFormatter alloc] init]; [df setDateFormat:@"MMMM d, yyyy h:mma"]; // API 1 TableViewCell *api1Cell = [tableView dequeueReusableCellWithIdentifier:@"YourAPI1Cell"]; // Do everything you need to do with the api1Cell // Use the index in 'indexPath.row' to get the object from you array // API1 Feed *feedLocal = [hArray objectAtIndex:indexPath.row]; // API1 NSString *dateString = [self timeSincePublished:feedLocal.published]; NSString *headlineText = [NSString stringWithFormat:@"%@", feedLocal.headline]; NSString *descriptionText = [NSString stringWithFormat:@"%@", feedLocal.description]; NSString *premiumText = [NSString stringWithFormat:@"%@", feedLocal.premium]; api1Cell.labelHeadline.text = [NSString stringWithFormat:@"%@", headlineText]; api1Cell.labelPublished.text = dateString; api1Cell.labelDescription.text = descriptionText; // SDWebImage API1 if ([feedLocal.images count] == 0) { // Not sure anything needed here } else { Images *imageLocal = [feedLocal.images objectAtIndex:0]; NSString *imageURL = [NSString stringWithFormat:@"%@", imageLocal.url]; NSString *imageWith = [NSString stringWithFormat:@"%@", imageLocal.width]; NSString *imageHeight = [NSString stringWithFormat:@"%@", imageLocal.height]; __weak UITableViewCell *wcell = cell; [cell.imageView setImageWithURL:[NSURL URLWithString:imageURL] placeholderImage:[UIImage imageNamed:@"X"] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType) { // Something }]; } cell = api1Cell; } else { // Date Change NSDateFormatter *df = [[NSDateFormatter alloc] init]; [df setDateFormat:@"MMMM d, yyyy h:mma"]; // API 2 MRWebListTableViewCellTwo *api2Cell = [tableView dequeueReusableCellWithIdentifier:@"YourAPI2Cell"]; // Do everything you need to do with the api2Cell // Remember to use 'indexPath.row - hArray.count' as the index for getting an object for your second array // API 2 Data *dataLocal = [iArray objectAtIndex:indexPath.row - hArray.count]; // API 2 NSString *dateStringI = [self timeSincePublished:dataLocal.created_time]; NSString *captionTextI = [NSString stringWithFormat:@"%@", dataLocal.caption.text]; NSString *usernameI = [NSString stringWithFormat:@"%@", dataLocal.user.username]; api2Cell.labelHeadline.text = usernameI; api2Cell.labelDescription.text = captionTextI; api2Cell.labelPublished.text = dateStringI; // SDWebImage API 2 if ([dataLocal.images count] == 0) { NSLog(@"Images Count: %lu", (unsigned long)dataLocal.images.count); // Not sure anything needed here } else { ImagesI *imageLocalI = [dataLocal.images objectAtIndex:0]; StandardResolutionI *standardResolutionLocal = [imageLocalI.standard_resolution objectAtIndex:0]; NSString *imageURLI = [NSString stringWithFormat:@"%@", standardResolutionLocal.url]; NSString *imageWithI = [NSString stringWithFormat:@"%@", standardResolutionLocal.width]; NSString *imageHeightI = [NSString stringWithFormat:@"%@", standardResolutionLocal.height]; // 11.2 __weak UITableViewCell *wcell = cell; [cell.imageView setImageWithURL:[NSURL URLWithString:imageURLI] placeholderImage:[UIImage imageNamed:@"X"] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType) { // Something }]; } cell = api2Cell; } return cell; } Feed.h @property (nonatomic, strong) Links *links; @property (nonatomic, strong) NSString *headline; @property (nonatomic, strong) NSString *source; @property (nonatomic, strong) NSDate *published; @property (nonatomic, strong) NSString *description; @property (nonatomic, strong) NSString *premium; @property (nonatomic, strong) NSArray *images; Data.h @property (nonatomic, strong) NSString *link; @property (nonatomic, strong) NSDate *created_time; @property (nonatomic, strong) UserI *user; @property (nonatomic, strong) NSArray *images; @property (nonatomic, strong) CaptionI *caption;

    Read the article

  • Objective-C how to check if a string is null

    - by norskben
    SO I wish to check to see if the item in my array [clientDataArray objectForKey:@"ClientCompany"] is nil. temp = [clientDataArray objectForKey:@"ClientCompany"]; if (temp != [NSNull null]) infofieldCompany.text = temp; So far I have been able to achieve this through the above code, but it does give me the warnings warning: 'NSArray' may not respond to'-objectForKey:' warning: comparison of distinct Objective-C types 'struct NSNull *' and 'struct NSString *' lacks a cast My main interest is the second warning, but the first warning also interest me. How should I adapt my above code?

    Read the article

  • Calculating string sizes on iPhone on a background thread

    - by jbrennan
    I've got some somewhat hefty string size calculations happening in my app (each one takes close to 500ms, and happens when the user scrolls to a new "page" in my app (like the Weather app). The delay only happens once per page, as the calculation only needs to be run once (and can even be cached for subsequent launches with the same data). Anyway, I still like to not block the UI for this type of work, as to me it screams using threads, but I know UIKit is not meant to be used from other threads. (I know NSString is not part of UIKit, but the string sizing methods are part of the UIKitAdditions...) So how should I go about doing this? What's the best way to not block the UI and do so safely?

    Read the article

  • NSMutableUrlRequest eats plus signs

    - by Mike
    I create NSMutableUrlRequest for sending data to server, add all necessary fields to it and then add the string for sending like this: [theRequest setHTTPBody:[postString dataUsingEncoding: NSUTF8StringEncoding]]; postString is a usual NSString. The problem is, when I receive this request at the server, all the plus (+) signs disappear from the http body. So if I had "abcde+fghj" on iPhone, I get "abcde fghj" on the server". Can this be some encoding problem from using dataUsingEncoding: NSUTF8StringEncoding? Or some NSMutableUrlRequest stripping feature? What can I do to make it stop stripping plus signs? I need to receive UTF8 strings at the server side.

    Read the article

  • How to use NSString drawInRect to centre text?

    - by Steve Folly
    How can I draw a string centred within a rect? I've started off with: (an extract from the drawRect method of my custom view) NSString* theString = ... [theString drawInRect:theRect withAttributes:0]; [theString release]; Now I'm assuming I need to set up some attributes. I've had a look through Apple's Cocoa documentation, but it's a bit overwhelming and can't find anything for how to add paragraph styles to the attributes. Also, I can only find horizontal alignment, what about vertical alignment? Thanks.

    Read the article

  • Getting info from NSData object

    - by Moshe
    How would I get returningResponse (into say, a NSString) from the following code: NSURLResponse* response; NSError* error; NSData* result = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:&response error:&error]; I think I can get the info that I need into a string but I can't call anything on response because it's null. Therefore, I assume that I need to call something on result. The problem is, I don't know what to call. (The URL request has been coded prior to the code sample. I know that that works.) I want to be able to detect if the request as successful.

    Read the article

  • Can't append space at end of UITextView

    - by Sam V
    I have a UITextView in which I want the initial value to be "@username " (notice the space after the username). This way the user can start typing right away without having to tap space. So I do: textView.text = [NSString stringWithFormat:@"@%@ ", username]; But it seems like it's impossible to have the UITextView text property ending with a space (it always gets stripped out). Am I correct? Is there any workaround for this? I tried using the \s char and no success.

    Read the article

  • -sizeWithFont Functions Differently on Device

    - by LucasTizma
    So I am seemingly encountering some strange behavior when using NSString's -sizeWithFont family of method calls depending on whether or not I'm invoking it on the iPhone Simulator or an actual device. Simply enough, when the receiver of the -sizeWithFont method call is nil, the resulting CGSize passed back on the Simulator is {0, 0}. However, on the device, it is the size of the bounding rectangle I specified in the method call. See the following log statements: Simulator: someString: (null) someStringSize: {0, 0} Device: someString: (null) someStringSize: {185, 3.40282e+38} The behavior on the Simulator is what I would expect. Not that this issue is difficult to circumvent, but 1) I'm a little confused why this family of functions would behave differently on the Simulator and an actual device, and 2) why does calling a method on a nil receiving return a particular result? Thanks for any pointers or insight you guys can provide! EDIT: I suppose I should mention that I'm building against the 3.1 SDK.

    Read the article

  • [[NSURL alloc] initFileURLWithPath:(NSString)] returns null

    - by Ajay Pandey
    NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:@"Opening" ofType:@"wav"]; NSURL *fileURL = [[NSURL alloc] initFileURLWithPath: soundFilePath]; NSLog(@"@ajay"); AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:nil]; [fileURL release]; [audioPlayer play]; i have inserted a wav file in my project.But NSURL *fileURL = [[NSURL alloc] initFileURLWithPath: soundFilePath]; returns NULL and console prints following: and application KILLS... Can someone help me?

    Read the article

  • formatting NSArray

    - by califguy
    So from the code below, I have managed to get the string *tempstring into an array chunk. Now chunk[0] contains 'a' while chunk[1] contains 'aa'. I am trying to format chunk[0] to '0a' which I can using the replaceObjectAtIndex method. Here's my question: How do I detect that chunk[0] is formatted as 'a' and not '0a'. I want to check all the indexes and make sure they have double digits and if not use a 0 to prefix it. NSString *tempstring = @"a-aa-bb"; NSMutableArray *chunk = [tempstring componentsSeparatedByString: @"-"]; NSLog(@"%@",[chunk objectAtIndex:0]);

    Read the article

  • objective c NSURL may not respond to +initFileURLWithPath

    - by caballo7
    I have two lines of code in the applicationDidFinishLaunching function: NSString *targetFilePath = @"/Users/bob/Documents/About_Stacks.pdf"; NSURL *targetFileURL = [NSURL initFileURLWithPath:targetFilePath]; and I am getting the warning (title) in the second line... I have no idea what I am doing wrong. This is an absurdly simply application... I have read other posts about reordering methods, but I am using classes provided by NS, nothing of my own. Any advice would be much appreciated. Thanks.

    Read the article

  • iPhone simulator app crashes when appending a string

    - by Franklyn Weber
    Hi, I'm a complete novice, so I'm probably missing something really easy, but I can't get my string appending to work. I add the 3rd character to typedDigit & it crashes - the method is called fine and typedDigit will get to 2 characters long. I think everything is declared properly in the header file. Code is - -(IBAction)digitPressed:(UIButton *)sender { NSString *digit = [[sender titleLabel] text]; // in this case, "0" - "9" if (userIsInMiddleOfTyping) { // typedDigit is already at least 1 character long typedDigit = [typedDigit stringByAppendingString:digit]; } else { // first character of typedDigit typedDigit = digit; userIsInMiddleOfTyping = YES; } } Many thanks for any help!

    Read the article

  • Ensure User has entered string in correct format?

    - by Daniel Granger
    Hi, Whats the best way to ensure the user has entered a valid time string such as: 5:24 5.4 102:30 102.5 It will be entered into a UITextField therefore will be in a NSString. I want to allow the user to enter the time in either hours and minutes (hh:mm) or hours and decimal minutes (hh.m). In the hours minutes example they should be able to enter as many hours as the like but only between 0 - 59 minutes. With the hours decimal minutes I want them to only be able to enter again as many hours as the like but decimal minutes can only be 0 - 9. Many Thanks

    Read the article

  • Sorting an NSArray of NSString

    - by Robert Eisinger
    Can someone please show me the code for sorting an NSMutableArray? I have the following NSMutableArray: NSMutableArray *arr = [[NSMutableArray alloc] init]; with elements such as "2", "4", "5", "1", "9", etc which are all NSString. I'd like to sort the list in descending order so that the largest valued integer is highest in the list (index 0). I tried the following: [arr sortUsingSelector:@selector(compare:)]; but it did not seem to sort my values properly. Can someone show me code for properly doing what I am trying to accomplish? Thanks!

    Read the article

  • Trouble with ID in NSString

    - by useboot
    I am trying to create something interesting in my application. So, I created an UILabel and I want to output new value. So, my code. NSString *test = @"13"; self.UserAge.text = @"Your age is %@", test; But it doesn't work. In Console-Command Mode I can do it with NSLog(); My result is "Your age is %@". But I need to output "Your age is 13". What do I should do with name? Sorry, if my question is easy for you. I am beginner. :) Thank you everyone who will answer on my question.

    Read the article

  • how to update database table in sqlite3 iphone

    - by Ajeet Kumar Yadav
    Hi I am new in Iphone i am developing application that is use database but i am face problem. In My application I am using table view. I am fetch the value from database in the table view this is done after that we also insert value throw text field in that table of database and display that value in table view.I am also use another table in database table name is Alootikki the value of table alootikki is display in other table view in application and user want to add this table alootikki value in first table of database and display that value in table view when we do this value is display only in the table view this is not write in the database table. when value is display and user want to add other data throw text field then only that add value is show first value is remove from table view. I am not able to solve this plz help me. The code is given bellow for database -(void)Data1 { //////databaseName = @"dataa.sqlite"; databaseName = @"Recipe1.sqlite"; NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDir = [documentPaths objectAtIndex:0]; databasePath =[documentsDir stringByAppendingPathComponent:databaseName]; [self checkAndCreateDatabase]; list1 = [[NSMutableArray alloc] init]; sqlite3 *database; if (sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) { if(addStmt == nil) { ////////////const char *sql = "insert into Dataa(item) Values(?)"; const char *sql = " insert into Slist(Incredients ) Values(?)"; if(sqlite3_prepare_v2(database, sql, -1, &addStmt, NULL) != SQLITE_OK) NSAssert1(0, @"Error while creating add statement. '%s'", sqlite3_errmsg(database)); } sqlite3_bind_text(addStmt, 1, [i UTF8String], -1, SQLITE_TRANSIENT); //sqlite3_bind_int(addStmt,1,i); // sqlite3_bind_text(addStmt, 1, [coffeeName UTF8String], -1, SQLITE_TRANSIENT); // sqlite3_bind_double(addStmt, 2, [price doubleValue]); if(SQLITE_DONE != sqlite3_step(addStmt)) NSAssert1(0, @"Error while inserting data. '%s'", sqlite3_errmsg(database)); else //SQLite provides a method to get the last primary key inserted by using sqlite3_last_insert_rowid coffeeID = sqlite3_last_insert_rowid(database); //Reset the add statement. sqlite3_reset(addStmt); // sqlite3_clear_bindings(detailStmt); //} } sqlite3_finalize(addStmt); addStmt = nil; sqlite3_close(database); } -(void)sopinglist { databaseName= @"Recipe1.sqlite"; NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDir = [documentPaths objectAtIndex:0]; databasePath =[documentsDir stringByAppendingPathComponent:databaseName]; [self checkAndCreateDatabase]; list1 = [[NSMutableArray alloc] init]; sqlite3 *database; if (sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) { if(addStmt == nil) { ///////////const char *sql = "insert into Dataa(item) Values(?)"; const char *sql = " insert into Slist(Incredients,Recipename,foodtype ) Values(?,?,?)"; ///////////// const char *sql =" Update Slist ( Incredients, Recipename,foodtype) Values(?,?,?)"; if(sqlite3_prepare_v2(database, sql, -1, &addStmt, NULL) != SQLITE_OK) NSAssert1(0, @"Error while creating add statement. '%s'", sqlite3_errmsg(database)); } /////for( NSString * j in k) sqlite3_bind_text(addStmt, 1, [k UTF8String], -1, SQLITE_TRANSIENT); //sqlite3_bind_int(addStmt,1,i); // sqlite3_bind_text(addStmt, 1, [coffeeName UTF8String], -1, SQLITE_TRANSIENT); // sqlite3_bind_double(addStmt, 2, [price doubleValue]); if(SQLITE_DONE != sqlite3_step(addStmt)) NSAssert1(0, @"Error while inserting data. '%s'", sqlite3_errmsg(database)); else //SQLite provides a method to get the last primary key inserted by using sqlite3_last_insert_rowid coffeeID = sqlite3_last_insert_rowid(database); //Reset the add statement. sqlite3_reset(addStmt); // sqlite3_clear_bindings(detailStmt); //} } sqlite3_finalize(addStmt); addStmt = nil; sqlite3_close(database); } -(void)Data { ////////////////databaseName = @"dataa.sqlite"; databaseName = @"Recipe1.sqlite"; NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDir = [documentPaths objectAtIndex:0]; databasePath =[documentsDir stringByAppendingPathComponent:databaseName]; [self checkAndCreateDatabase]; list1 = [[NSMutableArray alloc] init]; sqlite3 *database; if (sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) { if(detailStmt == nil) { const char *sql = "Select * from Slist "; if(sqlite3_prepare_v2(database, sql, -1, &detailStmt, NULL) == SQLITE_OK) { //NSLog(@"Hiiiiiii"); //sqlite3_bind_text(detailStmt, 1, [t1 UTF8String], -1, SQLITE_TRANSIENT); //sqlite3_bind_text(detailStmt, 2, [t2 UTF8String], -2, SQLITE_TRANSIENT); //sqlite3_bind_int(detailStmt, 3, t3); while(sqlite3_step(detailStmt) == SQLITE_ROW) { NSLog(@"Helllloooooo"); //NSString *item= [NSString stringWithUTF8String:(char *)sqlite3_column_text(detailStmt, 0)]; NSString *item= [NSString stringWithUTF8String:(char *)sqlite3_column_text(detailStmt, 0)]; char *str=( char*)sqlite3_column_text(detailStmt, 0); if( str) { item = [ NSString stringWithUTF8String:str ]; } else { item= @""; } //+ (NSString*)stringWithCharsIfNotNull: (char*)item /// { // if ( item == NULL ) // return nil; //else // return [[NSString stringWithUTF8String: item] //stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]]; //} //NSString *fame= [NSString stringWithUTF8String:(char *)sqlite3_column_text(detailStmt, 1)]; //NSString *cinemax = [NSString stringWithUTF8String:(char *)sqlite3_column_text(detailStmt, 2)]; //NSString *big= [NSString stringWithUTF8String:(char *)sqlite3_column_text(detailStmt, 3)]; //pvr1 = pvr; item1=item; //NSLog(@"%@",item1); data = [[NSMutableArray alloc] init]; list *animal=[[list alloc] initWithName:item1]; // Add the animal object to the animals Array [list1 addObject:animal]; //[list1 addObject:item]; } sqlite3_reset(detailStmt); } sqlite3_finalize(detailStmt); // sqlite3_clear_bindings(detailStmt); } } detailStmt = nil; sqlite3_close(database); } (void)recpies { /////////////////////databaseName = @"Data.sqlite"; databaseName = @"Recipe1.sqlite"; NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDir = [documentPaths objectAtIndex:0]; databasePath =[documentsDir stringByAppendingPathComponent:databaseName]; [self checkAndCreateDatabase]; list1 = [[NSMutableArray alloc] init]; sqlite3 *database; if (sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) { if(detailStmt == nil) { //////const char *sql = "Select * from Dataa"; const char *sql ="select *from alootikki"; if(sqlite3_prepare_v2(database, sql, -1, &detailStmt, NULL) == SQLITE_OK) { //NSLog(@"Hiiiiiii"); //sqlite3_bind_text(detailStmt, 1, [t1 UTF8String], -1, SQLITE_TRANSIENT); //sqlite3_bind_text(detailStmt, 2, [t2 UTF8String], -2, SQLITE_TRANSIENT); //sqlite3_bind_int(detailStmt, 3, t3); while(sqlite3_step(detailStmt) == SQLITE_ROW) { //NSLog(@"Helllloooooo"); //NSString *item= [NSString stringWithUTF8String:(char *)sqlite3_column_text(detailStmt, 0)]; NSString *item= [NSString stringWithUTF8String:(char *)sqlite3_column_text(detailStmt, 0)]; char *str=( char*)sqlite3_column_text(detailStmt, 0); if( str) { item = [ NSString stringWithUTF8String:str ]; } else { item= @""; } //NSString *fame= [NSString stringWithUTF8String:(char *)sqlite3_column_text(detailStmt, 1)]; //NSString *cinemax = [NSString stringWithUTF8String:(char *)sqlite3_column_text(detailStmt, 2)]; //NSString *big= [NSString stringWithUTF8String:(char *)sqlite3_column_text(detailStmt, 3)]; //pvr1 = pvr; item1=item; //NSLog(@"%@",item1); data = [[NSMutableArray alloc] init]; list *animal=[[list alloc] initWithName:item1]; // Add the animal object to the animals Array [list1 addObject:animal]; //[list1 addObject:item]; } sqlite3_reset(detailStmt); } sqlite3_finalize(detailStmt); // sqlite3_clear_bindings(detailStmt); } } detailStmt = nil; sqlite3_close(database); }

    Read the article

  • String formatting in cocoa

    - by lostInTransit
    Hi I am trying to send some text in an email from my cocoa app (by using Mail.app). Initially I tried using HTML to send properly formatted text. But the mailto: URL does not support html tags (even after setting headers) So I decided to use formatted string (left-aligning of string) This is what I have in my mailto: link's body argument NSMutableString *emailBody = [NSMutableString stringWithFormat:@"|%-35s", [@"Name" UTF8String]]; [emailBody appendFormat:@"|%-18s", [@"Number" UTF8String]]; [emailBody appendString:@"|Notes\n"]; [emailBody appendString:@"----------------------------------------------------------------------------------------------------"]; for(int i = 0; i < [items count]; i++){ NSDictionary *props = [items objectAtIndex:i]; NSMutableString *emailData = [NSMutableString stringWithFormat:@"|%-35s", [[props valueForKey:@"name"] UTF8String]]; [emailData appendFormat:@"|$ %-16s", [[props valueForKey:@"number"] UTF8String]]; [emailData appendString:[props valueForKey:@"notes"]]; [emailBody appendString:@"\n"]; [emailBody appendString:emailData]; } This does give me padded text but they all don't necessarily take up the same space (for instance if there is an O in the text, it takes up more space than others and ruins the formatting) Is there another sure-shot way to format text using just NSString? Thanks

    Read the article

  • Extract known pattern substring from NSString (without regex)

    - by d11wtq
    I'm really tempted to drop RegexKit (or my own libpcre wrapper) into my project in order to do this, but before I do that I want to know how Cocoa developers manage to do half of this basic stuff without really convoluted code or without linking with RegexKit or another regular expression library. I find it gobsmacking that Cocoa does not include any regular expression matching features. I've so accustomed to using regular expressions for all kinds of things that I'm lost without them. I can do what I need without them, but the code would be rather convoluted. So, Cocoa devs, I ask you, what's the "Cocoa way" to do this... The problem is an everyday problem in programming as far as I'm concerned. Cocoa must have ways of doing this with the built-in features. Note that the position of the elements I want to match changes, and sometimes "quotes" are present. Whitespace is variable. Take the following strings: Content-Type: application/xml; charset=utf-8 Content-Type: text/html; charset="iso-8859-1" Content-Type: text/plain; charset=us-ascii Content-Type: text/plain; name="example.txt"; charset=utf-8 From all of these strings, how would you go about determining the mime type (e.g. text/plain) and the charset (e.g. utf-8) using just the built-in Cocoa classes? I'd end up performing a series of -rangeOfString: and substring calls, with conditional checks to deal with the optional quotes etc. Is there a way to do this with NSScanner? The NSScanner class seems to have a pretty naive API to me. Something like C's sscanf() that works for NSString objects would be an ideal fit. Most of my string parsing needs are simple such as this example so maybe regular expressions, while I'm accustomed to them, are overkill?

    Read the article

  • Date from String using NSDateFormatter regardless 12h-24h setting

    - by maxf99
    Hello everybody, Today my question is about date formats and strings. My application downloads some strings representing dates from the internet. The date format is always like this: "2010-05-24 at 20:45" I need to convert this string into an NSDate object in order to perform some date manipulations. I tried this code: NSString * dateString = @"2010-05-24 at 20:45" // actually downloaded from the internet NSDateFormatter * myDateFormatter = [[NSDateFormatter alloc] init]; [myDateFormatter setDateFormat:@"yyyy-MM-dd 'at' HH:mm"]; NSDate * dateFromString = [myDateFormatter dateFromString:dateString]; This seems to work perfectly fine as long as the iPhone is set to 24h clock. As long as I switch to 12h clock in the general settings the NSDate object is not created (and the application happily crashes) I have read others having similar problems but I don't seem to find a solution. Now the questions: It doesn't make sense to me that the NSDateFormatter is sensible to user settings as long as I am specifying which format it is supposed to use to parse the string (which is not modifiable because it comes from the web), what's the use of checking user settings? More important, how can I get my task performed (to get an NSDate object from the string regardless the user settings)?

    Read the article

  • iPhone SDK Programming - Working with a variable across 2 views

    - by SD
    I have what I hope is a fairly simple question about using the value from a variable across 2 views. I’m new to the iPhone SDK platform and the Model/View/Controller methodology. I’ve got background in VB.Net, some Php, but mostly SQL, so this is new ground for me. I’m building an app that has 3 views. For simplicity’s sake, I’ll call them View1, View2, View3. On View1 I have an NSString variable that I’ve declared in View1.h, and synthesized in View1.m. I’ll call it String1. View1.m uses a UITextField to ask the user for their name and then sets the value of String1 to that name (i.e. "Bill"). I would now like to use the value of String1 in View2. I'm not doing anything other than displaying the value ("Bill"), in a UILabel object in View2. Can someone tell me what the easiest way to accomplish that is? Many thanks in advance….

    Read the article

  • How to select one object from a NSArray?

    - by 0SX
    First of all Merry Christmas to everyone!!! Currently I have a NSArray that has parsed content in it. When I do a NSLog of the array it prints out 20 objects with the parsed content that I needed. Like so: 2010-12-24 20:27:32.170 TestProject[48914:298] SomeContent 2010-12-24 20:27:32.172 TestProject[48914:298] SomeContent1 2010-12-24 20:27:32.172 TestProject[48914:298] SomeContent2 2010-12-24 20:27:32.173 TestProject[48914:298] SomeContent3 2010-12-24 20:27:32.173 TestProject[48914:298] SomeContent4 2010-12-24 20:27:32.173 TestProject[48914:298] SomeContent5 2010-12-24 20:27:32.174 TestProject[48914:298] SomeContent6 2010-12-24 20:27:32.175 TestProject[48914:298] SomeContent7 2010-12-24 20:27:32.176 TestProject[48914:298] SomeContent8 2010-12-24 20:27:32.176 TestProject[48914:298] SomeContent9 2010-12-24 20:27:32.177 TestProject[48914:298] SomeContent10 2010-12-24 20:27:32.177 TestProject[48914:298] SomeContent11 2010-12-24 20:27:32.177 TestProject[48914:298] SomeContent12 2010-12-24 20:27:32.179 TestProject[48914:298] SomeContent13 2010-12-24 20:27:32.179 TestProject[48914:298] SomeContent14 2010-12-24 20:27:32.180 TestProject[48914:298] SomeContent15 2010-12-24 20:27:32.180 TestProject[48914:298] SomeContent16 2010-12-24 20:27:32.181 TestProject[48914:298] SomeContent17 2010-12-24 20:27:32.181 TestProject[48914:298] SomeContent18 2010-12-24 20:27:32.190 TestProject[48914:298] SomeContent19 However, I don't need every object at once. I need to be able to pick out one object at a time so I can put each object into a string of it's own. If anyone knows a easier way to do this then what I'm trying to please let me know. Anyways, I need to be able to choose just one object depending on what object I need. For example, let's say I only need object #5 and not all the array, how can this be done so I can put it into a string? I'm thinking I might have to use the index feature but I'm not sure how to set it up properly. Here is my NSArray that I'm working with: NSArray* myArray = [document selectElements: @"div.someContent"]; NSMutableArray* results = [NSMutableArray array]; for (Element* element in myArray){ NSString* snipet = [element contentsSource]; [results addObject: snipet]; NSLog(@"%@", snipet); } NSLog(@"%i",myArray.count); I've already spent several hours trying to achieve this but my knowledge with array's is limited even with me reading the documentation. :-( Any help is much appreciated. Thanks

    Read the article

  • how do you make a "concurrent queue safe" lazy loader (singleton manager) in objective-c

    - by Rich
    Hi, I made this class that turns any object into a singleton, but I know that it's not "concurrent queue safe." Could someone please explain to me how to do this, or better yet, show me the code. To be clear I want to know how to use this with operation queues and dispatch queues (NSOperationQueue and Grand Central Dispatch) on iOS. Thanks in advance, Rich EDIT: I had an idea for how to do it. If someone could confirm it for me I'll do it and post the code. The idea is that proxies make queues all on their own. So if I make a mutable proxy (like Apple does in key-value coding/observing) for any object that it's supposed to return, and always return the same proxy for the same object/identifier pair (using the same kind of lazy loading technique as I used to create the singletons), the proxies would automatically queue up the any messages to the singletons, and make it totally thread safe. IMHO this seems like a lot of work to do, so I don't want to do it if it's not gonna work, or if it's gonna slow my apps down to a crawl. Here's my non-thread safe code: RMSingletonCollector.h // // RMSingletonCollector.h // RMSingletonCollector // // Created by Rich Meade-Miller on 2/11/11. // Copyright 2011 Rich Meade-Miller. All rights reserved. // #import <Foundation/Foundation.h> #import "RMWeakObjectRef.h" struct RMInitializerData { // The method may take one argument. // required SEL designatedInitializer; // data to pass to the initializer or nil. id data; }; typedef struct RMInitializerData RMInitializerData; RMInitializerData RMInitializerDataMake(SEL initializer, id data); @interface NSObject (SingletonCollector) // Returns the selector and data to pass to it (if the selector takes an argument) for use when initializing the singleton. // If you override this DO NOT call super. + (RMInitializerData)designatedInitializerForIdentifier:(NSString *)identifier; @end @interface RMSingletonCollector : NSObject { } + (id)collectionObjectForType:(NSString *)className identifier:(NSString *)identifier; + (id<RMWeakObjectReference>)referenceForObjectOfType:(NSString *)className identifier:(NSString *)identifier; + (void)destroyCollection; + (void)destroyCollectionObjectForType:(NSString *)className identifier:(NSString *)identifier; @end // ==--==--==--==--==Notifications==--==--==--==--== extern NSString *const willDestroySingletonCollection; extern NSString *const willDestroySingletonCollectionObject; RMSingletonCollector.m // // RMSingletonCollector.m // RMSingletonCollector // // Created by Rich Meade-Miller on 2/11/11. // Copyright 2011 Rich Meade-Miller. All rights reserved. // #import "RMSingletonCollector.h" #import <objc/objc-runtime.h> NSString *const willDestroySingletonCollection = @"willDestroySingletonCollection"; NSString *const willDestroySingletonCollectionObject = @"willDestroySingletonCollectionObject"; RMInitializerData RMInitializerDataMake(SEL initializer, id data) { RMInitializerData newData; newData.designatedInitializer = initializer; newData.data = data; return newData; } @implementation NSObject (SingletonCollector) + (RMInitializerData)designatedInitializerForIdentifier:(NSString *)identifier { return RMInitializerDataMake(@selector(init), nil); } @end @interface RMSingletonCollector () + (NSMutableDictionary *)singletonCollection; + (void)setSingletonCollection:(NSMutableDictionary *)newSingletonCollection; @end @implementation RMSingletonCollector static NSMutableDictionary *singletonCollection = nil; + (NSMutableDictionary *)singletonCollection { if (singletonCollection != nil) { return singletonCollection; } NSMutableDictionary *collection = [[NSMutableDictionary alloc] initWithCapacity:1]; [self setSingletonCollection:collection]; [collection release]; return singletonCollection; } + (void)setSingletonCollection:(NSMutableDictionary *)newSingletonCollection { if (newSingletonCollection != singletonCollection) { [singletonCollection release]; singletonCollection = [newSingletonCollection retain]; } } + (id)collectionObjectForType:(NSString *)className identifier:(NSString *)identifier { id obj; NSString *key; if (identifier) { key = [className stringByAppendingFormat:@".%@", identifier]; } else { key = className; } if (obj = [[self singletonCollection] objectForKey:key]) { return obj; } // dynamic creation. // get a class for Class classForName = NSClassFromString(className); if (classForName) { obj = objc_msgSend(classForName, @selector(alloc)); // if the initializer takes an argument... RMInitializerData initializerData = [classForName designatedInitializerForIdentifier:identifier]; if (initializerData.data) { // pass it. obj = objc_msgSend(obj, initializerData.designatedInitializer, initializerData.data); } else { obj = objc_msgSend(obj, initializerData.designatedInitializer); } [singletonCollection setObject:obj forKey:key]; [obj release]; } else { // raise an exception if there is no class for the specified name. NSException *exception = [NSException exceptionWithName:@"com.RMDev.RMSingletonCollector.failed_to_find_class" reason:[NSString stringWithFormat:@"SingletonCollector couldn't find class for name: %@", [className description]] userInfo:nil]; [exception raise]; [exception release]; } return obj; } + (id<RMWeakObjectReference>)referenceForObjectOfType:(NSString *)className identifier:(NSString *)identifier { id obj = [self collectionObjectForType:className identifier:identifier]; RMWeakObjectRef *objectRef = [[RMWeakObjectRef alloc] initWithObject:obj identifier:identifier]; return [objectRef autorelease]; } + (void)destroyCollection { NSDictionary *userInfo = [singletonCollection copy]; [[NSNotificationCenter defaultCenter] postNotificationName:willDestroySingletonCollection object:self userInfo:userInfo]; [userInfo release]; // release the collection and set it to nil. [self setSingletonCollection:nil]; } + (void)destroyCollectionObjectForType:(NSString *)className identifier:(NSString *)identifier { NSString *key; if (identifier) { key = [className stringByAppendingFormat:@".%@", identifier]; } else { key = className; } [[NSNotificationCenter defaultCenter] postNotificationName:willDestroySingletonCollectionObject object:[singletonCollection objectForKey:key] userInfo:nil]; [singletonCollection removeObjectForKey:key]; } @end RMWeakObjectRef.h // // RMWeakObjectRef.h // RMSingletonCollector // // Created by Rich Meade-Miller on 2/12/11. // Copyright 2011 Rich Meade-Miller. All rights reserved. // // In order to offset the performance loss from always having to search the dictionary, I made a retainable, weak object reference class. #import <Foundation/Foundation.h> @protocol RMWeakObjectReference <NSObject> @property (nonatomic, assign, readonly) id objectRef; @property (nonatomic, retain, readonly) NSString *className; @property (nonatomic, retain, readonly) NSString *objectIdentifier; @end @interface RMWeakObjectRef : NSObject <RMWeakObjectReference> { id objectRef; NSString *className; NSString *objectIdentifier; } - (RMWeakObjectRef *)initWithObject:(id)object identifier:(NSString *)identifier; - (void)objectWillBeDestroyed:(NSNotification *)notification; @end RMWeakObjectRef.m // // RMWeakObjectRef.m // RMSingletonCollector // // Created by Rich Meade-Miller on 2/12/11. // Copyright 2011 Rich Meade-Miller. All rights reserved. // #import "RMWeakObjectRef.h" #import "RMSingletonCollector.h" @implementation RMWeakObjectRef @dynamic objectRef; @synthesize className, objectIdentifier; - (RMWeakObjectRef *)initWithObject:(id)object identifier:(NSString *)identifier { if (self = [super init]) { NSString *classNameForObject = NSStringFromClass([object class]); className = classNameForObject; objectIdentifier = identifier; objectRef = object; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(objectWillBeDestroyed:) name:willDestroySingletonCollectionObject object:object]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(objectWillBeDestroyed:) name:willDestroySingletonCollection object:[RMSingletonCollector class]]; } return self; } - (id)objectRef { if (objectRef) { return objectRef; } objectRef = [RMSingletonCollector collectionObjectForType:className identifier:objectIdentifier]; return objectRef; } - (void)objectWillBeDestroyed:(NSNotification *)notification { objectRef = nil; } - (void)dealloc { [[NSNotificationCenter defaultCenter] removeObserver:self]; [className release]; [super dealloc]; } @end

    Read the article

  • nsdata to nsstring to nsdata

    - by Jayshree
    Hello everybody. I am calling the webservices. The web service returns data in xml format. Now the problem is the xml data is not being received in proper format. In place of "<", "" it returns in html format like-(<) and (>) . So i assigned the xmldata to a NsMutableString and replaced the escape characters so that the format of xml data is proper. Then i reassigned the NSMutableString to NSData so that i can parse the tags. but the problem is the xmlparser stops right where the xml data is. Where i replaced the tags. it doesnt go further. can anybody make me understand what is going on???? This is the xml response from webservice that i called. <?xml version="1.0" encoding="ISO-8859-1"?><SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"> <SOAP-ENV:Body> <ns1:GetCustomerInfoResponse xmlns:ns1="http://aa.somewebservice.com/phpwebservice"> <return xsi:type="xsd:string"> &lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;&lt;customer&gt;&lt;id&gt;1&lt;/id&gt;&lt;customername&gt;Hitesh&lt;/customername&gt;&lt;phonenumber&gt;98989898&lt;/phonenumber&gt;&lt;/customer&gt; </return> </ns1:GetCustomerInfoResponse> </SOAP-ENV:Body> </SOAP-ENV:Envelope> And this is after i replaced the tags. <?xml version="1.0" encoding="ISO-8859-1"?><SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"> <SOAP-ENV:Body> <ns1:GetCustomerInfoResponse xmlns:ns1="http://a.somewebservice.com/phpwebservice"> <return xsi:type="xsd:string"> <?xml version="1.0" encoding="utf-8"?> <customer><id>1</id><customername>Hitesh</customername><phonenumber>98989898</phonenumber></customer> </return> </ns1:GetCustomerInfoResponse> </SOAP-ENV:Body></SOAP-ENV:Envelope> Now the problem is while parsing the parser only goes upto return tag. And then it is stuck there. It doesnt go any further. So wat do i do? anybody care to help me?

    Read the article

  • String comparison in Objective-C

    - by james.ingham
    Hey, I've currently got a webserver set up which I communicate over SOAP with my iPhone app. I am returning a string containing a GUID and when I attempt to compare this with another string I get some strange results: Why would this not fire? Surely the two strings are a match? Thanks

    Read the article

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