sorting array with date in string without comparator - ios6

everyone
I am in another mess. I need to sort an array with date in strings and names corresponding to their birthday (date).And then view it in table view. Is there any way?

Use this function to sort by birthday. And make Conditions as per your requirements.
-(void)sortAllDate:(NSMutableArray *)arrayToSort
{
NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:#"self"
ascending:YES];
NSArray *descriptors = [NSArray arrayWithObject:descriptor];
NSArray *reverseOrder = [arrayToSort sortedArrayUsingDescriptors:descriptors];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"MM-dd-yyyy"];
NSMutableArray *temp = [[NSMutableArray alloc] init];
for (int k=0; k<[reverseOrder count]; k++) {
for(int m=0;m<[frdArray count];m++)
{
NSString *dateStr = [NSString stringWithFormat:#"%#",[[frdArray objectAtIndex:m] birthday]];
if([dateStr isEqualToString:[formatter stringFromDate:[reverseOrder objectAtIndex:k]]])
{
[temp addObject:[frdArray objectAtIndex:m]];
}
}
}
frdArray = temp;
}

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"MM/dd"];
sortedDataSource = [BdayArr sortedArrayUsingComparator:^NSComparisonResult(NSDictionary *obj1, NSDictionary *obj2) {
NSDate *d1 = [formatter dateFromString:obj1[kKeyDOB]];
NSDate *d2 = [formatter dateFromString:obj2[kKeyDOB]];
return [d1 compare:d2]; // ascending order
//return [d2 compare:d1]; // descending order
}];
NSLog(#"%#",sortedDataSource);
}

Related

How to load URL on UITableViewCell touch

New at this, just trying to make a link load if a certain UITableView cell is touched.
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:nil];
NSArray *deals = [dic objectForKey:#"deals"];
NSDictionary *dealOne = [deals objectAtIndex:0];
NSString *url = [dealOne objectForKey:#"url"];
UITouch *touch = [[event allTouches] anyObject];
if([touch isKindOfClass:[UITableViewCell class]])
{
UITableViewCell *cell;
CGPoint location = [touch locationInView: self.view];
cell.center = location;
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];
}
NSLog(#"TABLECELL TOUCHED");
}
Solved using the following. In this case, I wanted to have a link load when the cell was touched for "finalDealOne." When the cell is double-tapped, the link loads.
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:nil];
NSArray *deals = [dic objectForKey:#"deals"];
NSDictionary *dealOne = [deals objectAtIndex:0];
NSString *title = [dealOne objectForKey:#"title"];
NSString *finalDealOne = [NSString stringWithFormat:#"Deal One:\n\n''%#''\n\nDouble tap here to redeem offer.",title];
(NSIndexPath *)indexPath
UITapGestureRecognizer *tapped = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(finalDealOne)];
tapped.numberOfTapsRequired = 2;
[cell addGestureRecognizer:tapped];
}
To make this work, I included the following reference:
- (void)finalDealOne
{
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:nil];
NSArray *deals = [dic objectForKey:#"deals"];
NSDictionary *dealOne = [deals objectAtIndex:0];
NSString *url = [dealOne objectForKey:#"url"];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];
}

Want to check whether EKEventStore permission exist on ios6 device

Want to check whether EKEventStore permission exist on ios6 device.
EKEventStore *eventStore = [[UpdateManager sharedUpdateManager] eventStore];
if ([eventStore respondsToSelector:#selector(requestAccessToEntityType:completion:)])
{
[eventStore requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error)
{
if (granted)
{
addEventBlock();
}
else
{
NSLog(#"Not granted");
}
}];
}
This code works only at the first time.
Use like this.
- (IBAction)btnAddFromDBTouched:(id)sender {
void (^addEventBlock)();
addEventBlock = ^
{
self.eventStore = [[EKEventStore alloc] init];
self.eventsList = [[NSMutableArray alloc] initWithArray:0];
self.defaultCalendar = [self.eventStore defaultCalendarForNewEvents];
NSDate *startDate = [NSDate date];
// endDate is 1 day = 60*60*24 seconds = 86400 seconds from startDate
NSDate *endDate = [NSDate dateWithTimeIntervalSinceNow:86400*365];
// Create the predicate. Pass it the default calendar.
NSArray *calendarArray = [NSArray arrayWithObject:defaultCalendar];
NSPredicate *predicate = [self.eventStore predicateForEventsWithStartDate:startDate endDate:endDate
calendars:calendarArray];
NSArray *events = [self.eventStore eventsMatchingPredicate:predicate];
nmfChooseEvent *myView = [[nmfChooseEvent alloc] init];
[myView setTableSource:events];
[self presentModalViewController:myView animated:YES];
myView.mainView=self;
return;
};
if ([eventStore respondsToSelector:#selector(requestAccessToEntityType:completion:)])
{
[eventStore requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error)
{
if (granted)
{
addEventBlock();
}
else
{
dispatch_async(dispatch_get_main_queue(), ^{
UIAlertView *myView = [[UIAlertView alloc] initWithTitle:#"warning" message:#"To be Able to Use This Function, You Must Authorize xxx in Settings>>Privacy>>Calendars Section." delegate:nil cancelButtonTitle:"OK" otherButtonTitles:nil, nil];
[myView show];
});
}
}];
}
else
{
addEventBlock();
}
}

by Adding Polyline(path) on MKMapview crashing the app in ios6

I have a requirement to adding a path in my MKMapview between two annotation pin. There is no issue with ios 5 or older but when i try to run app in ios 6 app is surprisingly quit. below is my code. If there is any correction in my code then please suggest me.
1.So my question is suggest the best way how to decrees memory in my following code so that i can solve crash in my Application.
- (void)viewDidLoad
{
NVPolylineAnnotation *annotation = [[NVPolylineAnnotation alloc] initWithPoints:pathArray mapView:_mapView];
[_mapView addAnnotation:annotation];
[annotation release];
[pathArray removeAllObjects];
}
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation
{
NSLog(#"%s",__FUNCTION__);
if ([annotation isKindOfClass:[NVPolylineAnnotation class]])
{
NSLog(#"=========ANOTATION=========NVPolylineAnnotationView START");
//ann=[ann initWithAnnotation:annotation mapView:_mapView];
NVPolylineAnnotationView *ann=[[NVPolylineAnnotationView alloc] init];
return [[ann initWithAnnotation:annotation mapView:_mapView] autorelease];//[[[NVPolylineAnnotationView alloc] initWithAnnotation:annotation mapView:_mapView] autorelease];
}
else if([annotation isKindOfClass:[MapViewAnnotation class]])
{
MKPinAnnotationView *annView=[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:#"pointers"] ;
// annView.rightCalloutAccessoryView = [UIButton buttonWithType: UIButtonTypeDetailDisclosure];
annView.animatesDrop=NO;
annView.canShowCallout = TRUE;
return [annView autorelease];
}
else if([annotation isKindOfClass:[PlacePin class]])
{
{
MKPinAnnotationView *pinView = nil;
if(annotation != mapView.userLocation)
{
static NSString *defaultPinID = #"com.invasivecode.pin";
pinView = (MKPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:defaultPinID];
if ( pinView == nil )
pinView = [[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:defaultPinID] autorelease];
pinView.pinColor = MKPinAnnotationColorGreen;
pinView.canShowCallout = YES;
pinView.animatesDrop = NO;
}
else {
[mapView.userLocation setTitle:#"I am here"];
}
return pinView;
}
}
return nil;
}
- (void) mapView:(MKMapView *)mapView didAddAnnotationViews:(NSArray *)views
{
NSLog(#"%s",__FUNCTION__);
// fixes that some marker are behind the polyline
for (int i=0; i<[views count]; i++)
{
MKAnnotationView *view = [views objectAtIndex:i];
if ([view isKindOfClass:[NVPolylineAnnotationView class]])
{
[[view superview] sendSubviewToBack:view];
/* In iOS version above 4.0 we need to update the polyline view after it
has been added to the mapview and it ready to be displayed. */
NSString *reqSysVer = #"4.0";
NSString *currSysVer = [[UIDevice currentDevice] systemVersion];
if ([currSysVer compare:reqSysVer options:NSNumericSearch] != NSOrderedAscending)
{
[self updatePolylineAnnotationView];
}
}
}
NSLog(#"----------didAddAnnotationViews");
}
- (void)updatePolylineAnnotationView
{
NSLog(#"%s",__FUNCTION__);
MKAnnotationView *annotationView = [views objectAtIndex:0];
id <MKAnnotation> mp = [annotationView annotation];
[mapView selectAnnotation:mp animated:NO];
*/
for (NSObject *a in [_mapView annotations])
{
if ([a isKindOfClass:[NVPolylineAnnotation class]])
{
NVPolylineAnnotation *polyline = (NVPolylineAnnotation *)a;
NSObject *pv = (NSObject *)[_mapView viewForAnnotation:polyline];
if ([pv isKindOfClass:[NVPolylineAnnotationView class]])
{
NVPolylineAnnotationView *polylineView =
(NVPolylineAnnotationView *)[_mapView viewForAnnotation:polyline];
[polylineView regionChanged];
}
}
}
}

Search bar and search display controller with segue

Never called when a search table cell is tapped
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([segue.identifier isEqualToString:#"Show Detail"])
{
Player *player = [self.fetchedResultsController objectAtIndexPath:[self.tableView indexPathForSelectedRow]];
[segue.destinationViewController setPlayer:player];
}
}
This filters the list correctly, but the prepareForSegue is never called when a search table cell is tapped.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Player Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
if (tableView == self.tableView)
{
// normal table view population
Player *player = [self.fetchedResultsController objectAtIndexPath:indexPath];
cell.textLabel.text = [[NSString alloc] initWithFormat:#"#%# %# %#", player.number, player.firstName, player.lastName];
cell.detailTextLabel.text = [[NSString alloc] initWithFormat:#"%#", player.position];
[cell.imageView setImageWithURL:[NSURL URLWithString:player.photo] placeholderImage:[UIImage imageNamed:#"playerplaceholder.jpg"]];
}
else if(tableView == self.searchDisplayController.searchResultsTableView)
{
// search view population
Player *player = [self.filteredFetchedResultsController objectAtIndexPath:indexPath];
cell.textLabel.text = [[NSString alloc] initWithFormat:#"#%# %# %#", player.number, player.firstName, player.lastName];
cell.detailTextLabel.text = [[NSString alloc] initWithFormat:#"%#", player.position];
[cell.imageView setImageWithURL:[NSURL URLWithString:player.photo] placeholderImage:[UIImage imageNamed:#"playerplaceholder.jpg"]];
}
return cell;
}
you need to put IF that check if the search have results.
like in this code:
if ([[segue identifier]isEqualToString:#"ShowDetails"])
{
ShowDetailsViewController *sdvc = (ShowDetailsViewController *)[segue destinationViewController];
NSIndexPath *indexPath = [[self tableView] indexPathForSelectedRow];
Books *selectedBooks = nil;
if(self.searchDisplayController.active)
selectedBooks = (Books *)[[self searchResults]objectAtIndex:[[[[self searchDisplayController]searchResultsTableView]indexPathForSelectedRow]row]];
else
selectedBooks = (Books *)[[self fetchResultsController] objectAtIndexPath:indexPath];
sdvc.currentBooks = selectedBooks;
}

Custom swipe function in UITableViewCell doesn't work

I need to add the count in the uitableviewcell in a such a way that when I trigger the swipe function the count should be incremented in the corresponding cell and while tapping the count should be decremented.
(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = nil;
NSString *CellIdentifier = #"sample";
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
}
UISwipeGestureRecognizer *recognizer;
recognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(handleTapFrom:)];
[self addGestureRecognizer:recognizer];
self.tapRecognizer = (UITapGestureRecognizer *)recognizer;
recognizer.delegate = self;
[recognizer release];
recognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:#selector(handleSwipeFrom:)];
[self addGestureRecognizer:recognizer];
[recognizer release];
UILabel *cookieLabel = [[UILabel alloc] initWithFrame:CGRectMake(5,5, 120,30)];
cookieLabel.text = #"hello";
cookieLabel.font = [UIFont systemFontOfSize:15.0f];
cookieLabel.textColor = [UIColor blackColor];
cookieLabel.backgroundColor = [UIColor redColor];
[cell.contentView addSubview:cookieLabel];
[cookieLabel release];
cell.selectionStyle = UITableViewCellSelectionStyleGray;
costLabel = [[UILabel alloc] initWithFrame:CGRectMake( 200, 5, 230, 30)];
//costLabel.text = handleSwipeFrom:;
costLabel.font = [UIFont systemFontOfSize:15.0f];
costLabel.textColor = [UIColor blackColor];
costLabel.backgroundColor = [UIColor greenColor];
[cell.contentView addSubview:costLabel];
[costLabel release];
[self setUserInteractionEnabled:YES];
return cell;
}
Don't add the UISwipeGestureRecognizer to the cell. Add it to the UITableView.
I used TISwipeableTableView as a base and modified it heavily to work correctly (they did their own touch handling, which resulted in a "weird, unnative" feeling)
- (void)didSwipe:(UIGestureRecognizer *)gestureRecognizer {
if ([MRUserDefaults sharedMRUserDefaults].isSwipeMenuEnabled) {
if (gestureRecognizer.state == UIGestureRecognizerStateEnded) {
CGPoint swipeLocation = [gestureRecognizer locationInView:self];
NSIndexPath *swipedIndexPath = [self indexPathForRowAtPoint:swipeLocation];
TISwipeableTableViewCell* swipedCell = (TISwipeableTableViewCell *)[self cellForRowAtIndexPath:swipedIndexPath];
if ([swipedCell isKindOfClass:[TISwipeableTableViewCell class]]) {
if (![swipedIndexPath isEqual:indexOfVisibleBackView]) {
[self hideVisibleBackView:YES];
[swipedCell revealBackView];
[self setIndexOfVisibleBackView:swipedIndexPath];
if (swipeDelegate && [swipeDelegate respondsToSelector:#selector(tableView:didSwipeCellAtIndexPath:)]){
[swipeDelegate tableView:self didSwipeCellAtIndexPath:[self indexPathForRowAtPoint:swipeLocation]];
}
}
}
}
}
}
- (id)initWithFrame:(CGRect)frame style:(UITableViewStyle)style {
if ((self = [super initWithFrame:frame style:style])) {
if ([MRUserDefaults sharedMRUserDefaults].isSwipeMenuEnabled) {
UIGestureRecognizer *swipeGesture = [[[UISwipeGestureRecognizer alloc] initWithTarget:self action:#selector(didSwipe:)] autorelease];
[self addGestureRecognizer:swipeGesture];
}
}
return self;
}
This should get you started.
[cell addGestureRecognizer:recognizer]

Resources