Using UICollectionReusableView to group Cells - ios

I'm having trouble updating my old code which made synchronous JSOn calls to a new one which makes asynchronous calls using AFNetworking.
In my old code I was grouping cells with a UICollectionReusableView using a date string ("release_date"), all of this was done in the viewDidLoad. Now with AFNetworking I moved everything out of the viewDidLoad, so I'm stuck trying to figure out how to merge my old code with my new one.
This is the new code I have to parse my JSON with AFNetworking:
- (void)viewDidLoad
{
[super viewDidLoad];
self.upcomingReleases = [[NSMutableArray alloc] init];
[self makeReleasesRequests];
[self.collectionView registerClass:[ReleaseCell class] forCellWithReuseIdentifier:#"ReleaseCell"];
}
-(void)makeReleasesRequests //AFNetworking Call
{
NSURL *url = [NSURL URLWithString:#"http://www.soleresource.com/upcoming.json"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
operation.responseSerializer = [AFJSONResponseSerializer serializer];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"#");
self.upcomingReleases = [responseObject objectForKey:#"upcoming_releases"];
[self.collectionView reloadData];
} failure:nil];
[operation start];
}
Code I had in my viewDidLoad before I started using AFNetworking to make JSON calls and "group" my cells:
- (void)viewDidLoad
{
[super viewDidLoad];
NSURL *upcomingReleaseURL = [NSURL URLWithString:#"http://www.soleresource.com/upcoming.json"];
NSData *jsonData = [NSData dataWithContentsOfURL:upcomingReleaseURL];
NSError *error = nil;
NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
NSArray *upcomingReleasesArray = [dataDictionary objectForKey:#"upcoming_releases"];
//This is the dateFormatter we'll need to parse the release dates
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"];
NSTimeZone *est = [NSTimeZone timeZoneWithAbbreviation:#"EST"];
[dateFormatter setTimeZone:est];
[dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:#"en_US"]]; //A bit of an overkill to avoid bugs on different locales
//Temp array where we'll store the unsorted bucket dates
NSMutableArray *unsortedReleaseWeek = [[NSMutableArray alloc] init];
NSMutableDictionary *tmpDict = [[NSMutableDictionary alloc] init];
for (NSDictionary *upcomingReleaseDictionary in upcomingReleasesArray) {
//We find the release date from the string
NSDate *releaseDate = [dateFormatter dateFromString:[upcomingReleaseDictionary objectForKey:#"release_date"]];
//We create a new date that ignores everything that is not the actual day (ignoring stuff like the time of the day)
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components =
[gregorian components:(NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit) fromDate:releaseDate];
//This will represent our releases "bucket"
NSDate *bucket = [gregorian dateFromComponents:components];
//We get the existing objects in the bucket and update it with the latest addition
NSMutableArray *releasesInBucket = [tmpDict objectForKey:bucket];
if (!releasesInBucket){
releasesInBucket = [NSMutableArray array];
[unsortedReleaseWeek addObject:bucket];
}
UpcomingRelease *upcomingRelease = [UpcomingRelease upcomingReleaseWithName:[upcomingReleaseDictionary objectForKey:#"release_name"]];
upcomingRelease.release_date = [upcomingReleaseDictionary objectForKey:#"release_date"];
upcomingRelease.release_date = [upcomingReleaseDictionary objectForKey:#"release_date"];
[releasesInBucket addObject:upcomingRelease];
[tmpDict setObject:releasesInBucket forKey:bucket];
}
[unsortedReleaseWeek sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
NSDate* date1 = obj1;
NSDate* date2 = obj2;
//This will sort the dates in ascending order (earlier dates first)
return [date1 compare:date2];
//Use [date2 compare:date1] if you want an descending order
}];
self.releaseWeekDictionary = [NSDictionary dictionaryWithDictionary:tmpDict];
self.releaseWeek = [NSArray arrayWithArray:unsortedReleaseWeek];
[self.collectionView registerClass:[ReleaseCell class] forCellWithReuseIdentifier:#"ReleaseCell"];
}
CollectionViewCell
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
static NSString *identifier = #"Cell";
ReleaseCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
// Part of my new code AFNetworking
NSDictionary *upcomingReleaseDictionary = [self.upcomingReleases objectAtIndex:indexPath.row];
//
// I had this in my old code
UpcomingRelease *upcomingRelease = [self.releaseWeekDictionary objectForKey:self.releaseWeek[indexPath.section]][indexPath.row];
//
cell.release_name.text = upcomingRelease.release_name;
return cell;
}
This is the rest:
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
return [self.releaseWeek count];
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
return [[self.releaseWeekDictionary objectForKey:self.releaseWeek[section]] count];
}
-(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
ReleaseWeek *releaseWeek = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:#"releaseWeek" forIndexPath:indexPath];
//We tell the formatter to produce a date in the format "Name-of-the-month day"
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"MMMM dd"];
NSTimeZone *est = [NSTimeZone timeZoneWithAbbreviation:#"EST"];
[dateFormatter setTimeZone:est];
[dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:#"en_US"]];
//We read the bucket date and feed it to the date formatter
NSDate *releaseWeekDate = self.releaseWeek[indexPath.section];
releaseWeek.releaseDate.text = [[dateFormatter stringFromDate:releaseWeekDate] uppercaseString];
return releaseWeek;
}
I'm basically trying to figure out how to take the code that grouped my cells be the date string and integrate it with my new code.
Thanks.

Think MVC. Separate your model (the stuff that comes from the network) into a separate class that does the network operations, and grouping things into arrays and dictionaries. Your view controller should simply observe the model. You can use delegation or (my favorite) KVO to know when the model has updated data available. Then you just update your collection view. Your view controller should simply be an interface between the model and the views. If you separate things out this way you will find that it is much more natural, and you aren't fighting against the system.

You are closer than you think.
Simply put everything you used to do in viewDidLoad: (everything between the assignment of jsonData to the registration of your collection view class) into the callback block of your AFNetworking call (where jsonData is now called responseObject).
At the end of the callback block, simply invoke [self.collectionView reloadData], and the your collection view will reload itself (i.e. call numberOfItems and cellForItemAtIndexPath for each item).
In your UICollectionViewDataSource methods that return the number of sections and items, simply return 0 if the properties that hold your model are nil or empty.
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
// Correctly returns 0 if nil or empty.
return [self.releaseWeek count];
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
if(!self.releaseWeekDictionary[section] || !self.releaseWeek[section]) {
return 0;
}else{
return [self.releaseWeekDictionary[self.releaseWeek[section]] count];
}
}
Below should be the gravy code in your completion block.
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"#");
NSArray *upcomingReleasesArray = [dataDictionary objectForKey:#"upcoming_releases"];
//This is the dateFormatter we'll need to parse the release dates
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"];
NSTimeZone *est = [NSTimeZone timeZoneWithAbbreviation:#"EST"];
[dateFormatter setTimeZone:est];
[dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:#"en_US"]]; //A bit of an overkill to avoid bugs on different locales
//Temp array where we'll store the unsorted bucket dates
NSMutableArray *unsortedReleaseWeek = [[NSMutableArray alloc] init];
NSMutableDictionary *tmpDict = [[NSMutableDictionary alloc] init];
for (NSDictionary *upcomingReleaseDictionary in upcomingReleasesArray) {
//We find the release date from the string
NSDate *releaseDate = [dateFormatter dateFromString:[upcomingReleaseDictionary objectForKey:#"release_date"]];
//We create a new date that ignores everything that is not the actual day (ignoring stuff like the time of the day)
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components =
[gregorian components:(NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit) fromDate:releaseDate];
//This will represent our releases "bucket"
NSDate *bucket = [gregorian dateFromComponents:components];
//We get the existing objects in the bucket and update it with the latest addition
NSMutableArray *releasesInBucket = [tmpDict objectForKey:bucket];
if (!releasesInBucket){
releasesInBucket = [NSMutableArray array];
[unsortedReleaseWeek addObject:bucket];
}
UpcomingRelease *upcomingRelease = [UpcomingRelease upcomingReleaseWithName:[upcomingReleaseDictionary objectForKey:#"release_name"]];
upcomingRelease.release_date = [upcomingReleaseDictionary objectForKey:#"release_date"];
upcomingRelease.release_date = [upcomingReleaseDictionary objectForKey:#"release_date"];
[releasesInBucket addObject:upcomingRelease];
[tmpDict setObject:releasesInBucket forKey:bucket];
}
[unsortedReleaseWeek sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
NSDate* date1 = obj1;
NSDate* date2 = obj2;
//This will sort the dates in ascending order (earlier dates first)
return [date1 compare:date2];
//Use [date2 compare:date1] if you want an descending order
}];
self.releaseWeekDictionary = [NSDictionary dictionaryWithDictionary:tmpDict];
self.releaseWeek = [NSArray arrayWithArray:unsortedReleaseWeek];
[self.collectionView reloadData];
} failure:nil];
Edit: In your code, you were no longer assigning anything to upcomingReleases (block of commented code lines 91-102), and you were crashing referencing the index that didn't exist in the array. The fix is easy:
109: self.upcomingReleases = [dataDictionary objectForKey:#"upcoming_releases"];
122: for (NSDictionary *upcomingReleaseDictionary in self.upcomingReleases) {

Related

Performing Core Data Operations in self created multiple threads to save processing time

I have surfed a lot about performing core data operations in multiple threads but no good luck to solve my problem.
My code is such that I have to download a csv file after every ten minutes which contains each entry of 10 seconds. This file once downloaded is parsed and the contents are saved in database and then files are removed as then, when needed, I can fetch data from database.
Now, I have a huge existing content of more than a month for now which may extend to years also as time passes by, performing this huge task of saving new files to database and fetching objects from core data into an array for already downloaded files using a single thread is causing a huge processing time. Also, views in app needs to be adjusted with all previous data (They are basically plots of quantity vs time).
How can I achieve this in multiple threads and optimize my code processing time and reduce UI Blockage to minimum?
Please note that : Performing the task in background thread is not my concern as I in any case have to show graphs on the basis of total data. Please provide valuable advices.
EDIT: PERFORMED SOME MULTITHREADING
HERE IS THE NEW CODE,
- (void) downloadFiles:(NSString *)dataPath{
__block AppDelegate *appD = (AppDelegate *)[[UIApplication sharedApplication] delegate];
backgroundMOC = [[NSManagedObjectContext alloc] init];
[backgroundMOC setPersistentStoreCoordinator:[[appD managedObjectContext] persistentStoreCoordinator]];
if (parsedDetailsDataArrayForCurrentDay) {
parsedDetailsDataArrayForCurrentDay = nil;
}
if (parsedDetailsDataArrayForCurrentMonth) {
parsedDetailsDataArrayForCurrentMonth = nil;
}
if (parsedDetailsDataArrayForCurrentYear) {
parsedDetailsDataArrayForCurrentYear = nil;
}
parsedDetailsDataArrayForCurrentDay = [[NSMutableArray alloc] init];
parsedDetailsDataArrayForCurrentMonth = [[NSMutableArray alloc] init];
parsedDetailsDataArrayForCurrentYear = [[NSMutableArray alloc] init];
dispatch_group_t d_group = dispatch_group_create();
for (NSInteger i = 0; i <= (self.filesListArray.count - 1); i++) {
NSString *filePathOnPhone = [dataPath stringByAppendingString:[NSString stringWithFormat:#"/%#", [[self.filesListArray objectAtIndex:i] objectForKey:#"kCFFTPResourceName"]]];
NSFetchRequest *fetch = [NSFetchRequest fetchRequestWithEntityName:#"ParsedInfiDetails"];
NSString *nameToGet = [[self.filesListArray objectAtIndex:i] objectForKey:#"kCFFTPResourceName"];
NSLog(#"File Check: %#", nameToGet);
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"fileName = %#", nameToGet];
[fetch setPredicate:predicate];
NSError *error = nil;
NSArray *results = [backgroundMOC executeFetchRequest:fetch error:&error];
NSArray *definedResults = [results copy];
if(definedResults && (definedResults.count !=0)) {
NSLog(#"Entities with that name: %#", results);
#autoreleasepool {
NSArray *result = [[definedResults sortedArrayUsingDescriptors:[NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:#"modDate" ascending:YES]]] copy];
NSDate *specificDate = [NSDate date];
NSMutableArray *sortedDateArray = [[NSMutableArray alloc] init];
NSMutableArray *sortedDateCurrentYearArray = [[NSMutableArray alloc] init];
NSMutableArray *sortedDateCurrentMonthArray = [[NSMutableArray alloc] init];
for (int i = 0; i < result.count; i++) {
NSManagedObject *obj = [result objectAtIndex:i];
NSDate *objDate = [obj valueForKey:#"modDate"];
NSCalendar *gregorian = [NSCalendar currentCalendar];
NSDateComponents *components = [gregorian componentsInTimeZone:[NSTimeZone timeZoneWithAbbreviation:#"UTC"] fromDate:objDate];
NSInteger day = [components day];
NSInteger month = [components month];
NSInteger year = [components year];
NSDateComponents *specificComps = [[NSCalendar currentCalendar] components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear fromDate:specificDate];
NSInteger specificDay = [specificComps day];
NSInteger specificMonth = [specificComps month];
NSInteger specificYear = [specificComps year];
if(day == 24){
}
if (day == specificDay && month == specificMonth && year == (specificYear-2000)) {
[sortedDateArray addObject:obj];
}
NSDate *todayDate = [NSDate date];
NSDateComponents *componentsForToday = [[NSCalendar currentCalendar] components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear fromDate:todayDate];
NSInteger currentMonth = [componentsForToday month];
NSInteger currentYear = [componentsForToday year];
if (year == (currentYear-2000)) {
[sortedDateCurrentYearArray addObject:obj];
}
if (year == (currentYear -2000) && month == currentMonth) {
[sortedDateCurrentMonthArray addObject:obj];
}
}
NSMutableArray *sortedTimedArray = [[NSMutableArray alloc] initWithArray:[sortedDateArray sortedArrayUsingDescriptors:[NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:#"modTime" ascending:YES]]]];
NSMutableArray *sortedTimedCurrentYearArray = [[NSMutableArray alloc] initWithArray:[sortedDateCurrentYearArray sortedArrayUsingDescriptors:[NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:#"modTime" ascending:YES]]]];
NSMutableArray *sortedTimedCurrentMonthArray = [[NSMutableArray alloc] initWithArray:[sortedDateCurrentMonthArray sortedArrayUsingDescriptors:[NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:#"modTime" ascending:YES]]]];
[parsedDetailsDataArrayForCurrentDay addObjectsFromArray:sortedTimedArray];
[parsedDetailsDataArrayForCurrentYear addObjectsFromArray:sortedTimedCurrentYearArray];
[parsedDetailsDataArrayForCurrentMonth addObjectsFromArray:sortedTimedCurrentMonthArray];
}
} else {
NSLog(#"Error: %#", error);
NSString *threadName = [NSString stringWithFormat:#"%ld THREAD", (long)i];
dispatch_queue_t myQueue = dispatch_queue_create([threadName UTF8String], NULL);
dispatch_group_async(d_group, myQueue, ^{
NSManagedObjectContext *backgroundMOC1;
backgroundMOC1 = [[NSManagedObjectContext alloc] init];
[backgroundMOC1 setPersistentStoreCoordinator:[[appD managedObjectContext] persistentStoreCoordinator]];
NSLog(#"Entered Thread ");
BOOL success = [appD.ftpManager downloadFile:[[self.filesListArray objectAtIndex:i] objectForKey:#"kCFFTPResourceName"] toDirectory:[NSURL URLWithString:dataPath] fromServer:srv];
if (success) {
// dispatch_group_async(d_group, myQueue, ^{
NSMutableDictionary *dict = [appD.ftpManager progress];
NSString *filePath = [dataPath stringByAppendingString:[NSString stringWithFormat:#"/%#", [[self.filesListArray objectAtIndex:i] objectForKey:#"kCFFTPResourceName"]]];
CHCSVParser *parser = [[CHCSVParser alloc] initWithContentsOfCSVURL:[NSURL fileURLWithPath:filePath]];
[parser parse];
NSMutableArray *currentFileComponentsArray = [NSArray arrayWithContentsOfCSVURL:[NSURL fileURLWithPath:filePath]];
NSMutableArray *parsedDetailsEntitiesArray = [[NSMutableArray alloc] init];
for (int j = 1; j <= (currentFileComponentsArray.count-1); j++) {
NSArray *detailsArray = [currentFileComponentsArray objectAtIndex:j];
if (!(detailsArray.count < 32)) {
NSManagedObject *parsedDetails = [NSEntityDescription
insertNewObjectForEntityForName:#"ParsedInfiDetails"
inManagedObjectContext:[appD managedObjectContext]];
NSString *totalDateString = [NSString stringWithFormat:#"%# %#", [detailsArray objectAtIndex:0], [detailsArray objectAtIndex:1]];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = #"dd/MM/yyyy HH:mm:ss";
NSTimeZone *gmt = [NSTimeZone timeZoneWithAbbreviation:#"GMT"];
[dateFormatter setTimeZone:gmt];
NSDate *startDate = [dateFormatter dateFromString:totalDateString];
[parsedDetails setValue:startDate forKey:#"modDate"];
[parsedDetails setValue:startDate forKey:#"modTime"];
———————————————————————PERFORM PARSEDDETAILS STATEMENTS----------------
NSError *error;
NSLog(#"Saved File in Database: %#", [[self.filesListArray objectAtIndex:i] objectForKey:#"kCFFTPResourceName"]);
NSLog(#"Saved thread");
if (![backgroundMOC1 save:&error]) {
NSLog(#"Whoops, couldn't save: %#", [error localizedDescription]);
}
else{
if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
//if the download fails, we try to delete the empty file created by the stream.
[[NSFileManager defaultManager] removeItemAtPath:filePath error:nil];
//when data is stored in coredata remove the downloaded file.
}
[parsedDetailsEntitiesArray addObject:parsedDetails];
}
}
}
NSSet *set = [[NSSet alloc] initWithArray:parsedDetailsEntitiesArray];
[self.relevantInverId setValue:set forKey:#"infiDetails"];
NSDate *specificDate = [NSDate date];
#autoreleasepool {
NSMutableArray *sortedDateArray = [[NSMutableArray alloc] init];
NSMutableArray *sortedDateCurrentYearArray = [[NSMutableArray alloc] init];
NSMutableArray *sortedDateCurrentMonthArray = [[NSMutableArray alloc] init];
for (int i = 0; i < parsedDetailsEntitiesArray.count; i++) {
NSManagedObject *obj = [parsedDetailsEntitiesArray objectAtIndex:i];
NSDate *objDate = [obj valueForKey:#"modDate"];
NSCalendar *gregorian = [NSCalendar currentCalendar];
NSDateComponents *components = [gregorian componentsInTimeZone:[NSTimeZone timeZoneWithAbbreviation:#"UTC"] fromDate:objDate];
NSInteger day = [components day];
NSInteger month = [components month];
NSInteger year = [components year];
NSDateComponents *specificComps = [[NSCalendar currentCalendar] components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear fromDate:specificDate];
NSInteger specificDay = [specificComps day];
NSInteger specificMonth = [specificComps month];
NSInteger specificYear = [specificComps year];
if(day == 24){
}
if (day == specificDay && month == specificMonth && year == (specificYear-2000)) {
[sortedDateArray addObject:obj];
}
NSDate *todayDate = [NSDate date];
NSDateComponents *componentsForToday = [[NSCalendar currentCalendar] components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear fromDate:todayDate];
NSInteger currentMonth = [componentsForToday month];
NSInteger currentYear = [componentsForToday year];
if (year == (currentYear-2000)) {
[sortedDateCurrentYearArray addObject:obj];
}
if (year == (currentYear-2000) && month == currentMonth) {
[sortedDateCurrentMonthArray addObject:obj];
}
}
NSMutableArray *sortedTimedArray = [[NSMutableArray alloc] initWithArray:[sortedDateArray sortedArrayUsingDescriptors:[NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:#"modTime" ascending:YES]]]];
[parsedDetailsDataArrayForCurrentDay addObjectsFromArray:sortedTimedArray];
NSMutableArray *sortedTimedCurrentYearArray = [[NSMutableArray alloc] initWithArray:[sortedDateCurrentYearArray sortedArrayUsingDescriptors:[NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:#"modTime" ascending:YES]]]];
NSMutableArray *sortedTimedCurrentMonthArray = [[NSMutableArray alloc] initWithArray:[sortedDateCurrentMonthArray sortedArrayUsingDescriptors:[NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:#"modTime" ascending:YES]]]];
[parsedDetailsDataArrayForCurrentYear addObjectsFromArray:sortedTimedCurrentYearArray];
[parsedDetailsDataArrayForCurrentMonth addObjectsFromArray:sortedTimedCurrentMonthArray];
}
// });
}
});
}
BOOL isFileAlreadyPresent = [[NSFileManager defaultManager] fileExistsAtPath:filePathOnPhone];
}
NSMutableArray *sortedParsedDetailsArrayForCurrentDay = [[NSMutableArray alloc] initWithArray:[parsedDetailsDataArrayForCurrentDay sortedArrayUsingDescriptors:[NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:#"modTime" ascending:YES]]]];
NSDate *startDate ;
NSDate *endaDate;
dispatch_group_notify(d_group, dispatch_get_main_queue(), ^{
dispatch_async(dispatch_get_main_queue(), ^{
[self stopLogoSpin];
[hud dismiss];
});
NSLog(#"All background tasks are done!!");
});
}
Now, logs #"Entered Thread " is visible in log but, #"Saved File in Database: %#", [[self.filesListArray objectAtIndex:i] and #"Saved thread" are not called.
Also,
BOOL success = [appD.ftpManager downloadFile:[[self.filesListArray objectAtIndex:i] objectForKey:#"kCFFTPResourceName"] toDirectory:[NSURL URLWithString:dataPath] fromServer:srv];
helps download file with their seperate thread in the download method.
Should uncommenting below help?
// dispatch_group_async(d_group, myQueue, ^{
Main thread is intentionally made to wait but this block below is also never called:
dispatch_group_notify(d_group, dispatch_get_main_queue(), ^{
dispatch_async(dispatch_get_main_queue(), ^{
[self stopLogoSpin];
[radialHUD dismiss];
});
NSLog(#"All background tasks are done!!");
});
Please advice any modification and solution to problems above.
Optimised the code by moving all what is not needed in loop outside and the performing the looping operation using GCD.
dispatch_queue_t myOwnQueue = dispatch_queue_create([#"MyOwnQueue" UTF8String], NULL);
dispatch_apply(self.filesListArray.count, myOwnQueue, ^(size_t i) { });
This lead to reduction in time by half. However any further optimisations need to be seen.

Display Old messages of tableview using fetchedResultsController delegate at Top instead of bottom When Request Old Data

Currently I've a Tableview that when it loads it makes a request to Core-Data and grabs the first 10 Messages of the newer ones.
// Initialize Fetch Request
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:#"Chat"];
// Add Sort Descriptors
fetchRequest.fetchLimit = 10;
fetchRequest.predicate = [NSPredicate predicateWithFormat:#"room = %#", _roomid];
[fetchRequest setSortDescriptors:#[[NSSortDescriptor sortDescriptorWithKey:#"date_message" ascending:NO]]]; // YES;
// Initialize Fetched Results Controller
self.fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:nil cacheName:nil];
_fetchedResultsController.delegate = self;
// Perform Fetch
NSError *error = nil;
[self.fetchedResultsController performFetch:&error];
if (error) {
NSLog(#"Unable to perform fetch.");
NSLog(#"%#, %#", error, error.localizedDescription);
}
After I call them. Messages are shown properly under. But When I load (fetch older messages on demand) I use the following.
- (void)fetchOldMessages {
[self.fetchedResultsController.fetchRequest setSortDescriptors:#[[NSSortDescriptor sortDescriptorWithKey:#"date_message" ascending:NO]]];
_fetchedResultsController.fetchRequest.fetchLimit +=10;
NSError *error = nil;
[self.fetchedResultsController performFetch:&error];
if (error) {
NSLog(#"Unable to perform fetch.");
NSLog(#"%#, %#", error, error.localizedDescription);
}
[self.tableView reloadData];
}
The issue is that the Old messages are now being shown below instead of above the new messages. Also new inserted messages are shown at the top of the tableView instead of the bottom.
this is my IndexPath:
- (UITableViewCell*)tableView:(UITableView*)table cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
Chat *messageInfo = [self.fetchedResultsController objectAtIndexPath:indexPath];
NSString *CellIdentifier = #"fromMe";
FromMeTableViewCell *cell = [table dequeueReusableCellWithIdentifier:CellIdentifier];
cell.message_me.clipsToBounds = YES;
cell.message_me.layer.cornerRadius = 15;
cell.message_me.textContainerInset = UIEdgeInsetsMake(8.0, 8.0, 8.0, 8.0);
cell.message_me.text = messageInfo.message;
cell.message_date_me.text = [NSString stringWithFormat:#"%#", messageInfo.date_message];
cell.avatar_message_me.clipsToBounds = YES;
cell.avatar_message_me.layer.cornerRadius = cell.avatar_message_me.frame.size.width / 2;
cell.avatar_message_me.image = user_images[#"me"];
cell.message_me.backgroundColor = [UIColor colorWithRed:0.098 green:0.737 blue:0.611 alpha:1];
cell.message_me.textColor = [UIColor whiteColor]; //[UIColor whiteColor];
// Date Settings
NSDate *today = [[NSDate alloc]init];
NSDate *message_date = messageInfo.date_message;
NSDateFormatter *formatDate = [[NSDateFormatter alloc]init];
[formatDate setDateFormat:#"yyyy-MM-dd"];
NSString *today_string = [formatDate stringFromDate:today];
NSString *message_date_string = [formatDate stringFromDate:message_date];
// Make Date validation case is older display full date
if([today_string isEqualToString:message_date_string]){
NSDateFormatter *timeformat = [[NSDateFormatter alloc] init];
[timeformat setDateFormat:#"hh:mm a"];
NSDate *message_date = messageInfo.date_message;
NSString *string_date = [timeformat stringFromDate:message_date];
cell.message_date_me.text = [NSString stringWithFormat:#"Today at %#",[NSString stringWithFormat:#"%#",string_date]];
}
else {
NSDateFormatter *timeformat = [[NSDateFormatter alloc] init];
[timeformat setDateFormat:#"EEEE d hh:mm a"];
NSDate *message_date = messageInfo.date_message;
NSString *string_date = [timeformat stringFromDate:message_date];
cell.message_date_me.text = [NSString stringWithFormat:#"%#",[NSString stringWithFormat:#"%#",string_date]];
}
return cell;
}
This is when It first loads shows 5 Messages But the last message should be down ant not Above as you can see on the DATE
When I load more Data it shows the Messages in the right Order from new to older but the issue is that I want to show newer messages Below and Older messages Above.
Make your fetch request controller sorting ASCENDING to YES
[self.fetchedResultsController.fetchRequest
setSortDescriptors:#[[NSSortDescriptor
sortDescriptorWithKey:#"date_message" ascending:YES]]];

Sending multiple incrementing csv's from my app through e-mail

I've been racking my brain over this for the past week now and can't quite figure out how to go about this.
I currently have an app that takes in survey data, saves it as a csv file in the form of surveydata-mm-dd-yyyy. This usually goes out to events that last multiple days so a normal event weekend would be
surveydata-09-13-2014
surveydata-09-14-2014
surveydata-09-15-2014
Now I want the person who is at these events to be able to simply click a button that will prepend an e-mail with all those files which are being stored in the apps documents folder.
I have it all pretty much setup and functioning minus being able to tell the app to look for those files with those names and to include them in the e-mail.
Here is the code I have
- (IBAction)emailButton:(id)sender {
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"MM-dd-yyyy"];
NSString *dateString = [dateFormat stringFromDate:[NSDate date]];
NSString *path = [[self applicationDocumentsDirectory].path
stringByAppendingPathComponent:[NSString stringWithFormat:#"_SurveyData_%#.csv",dateString]];
/* if(![[NSFileManager defaultManager] fileExistsAtPath:path]) {*/
MFMailComposeViewController *mailer = [[MFMailComposeViewController alloc] init];
mailer.mailComposeDelegate = self;
[mailer setSubject:#"CSV File"];
[mailer setToRecipients:toRecipents];
[mailer addAttachmentData:[NSData dataWithContentsOfFile:#"_SurveyData_%#.csv"]
mimeType:#"text/csv"
fileName:#"FileName"];
[self presentModalViewController:mailer animated:YES];
//}
}
If somebody could please help me out as I feel like I'm so close I'm just waiting for it to all click and make sense.
Please let me know if I'm missing something or my code is too vague.
This is the code that i'm using to write the data to the CSV for better understanding of how it's all going down.
-(void)writeSurveyDataToCSV:(NSString *)text {
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"MM-dd-yyyy"];
NSString *dateString = [dateFormat stringFromDate:[NSDate date]];
NSString *path = [[self applicationDocumentsDirectory].path
stringByAppendingPathComponent:[NSString stringWithFormat:#"_SurveyData_%#.csv",dateString]];
if(![[NSFileManager defaultManager] fileExistsAtPath:path]) {
NSString *header = #" gender,age,zip code,duration(sec), own a bike?,response1,response2,response3,response4,response5,response6, response7, response8, response9\n";
[header writeToFile:path atomically:YES
encoding:NSUTF8StringEncoding error:nil];
}
text = [text stringByAppendingString:#"\n"];
NSFileHandle *fileHandle = [NSFileHandle fileHandleForWritingAtPath:path];
[fileHandle seekToEndOfFile];
[fileHandle writeData:[text dataUsingEncoding:NSUTF8StringEncoding]];
}
EDIT: Thanks to Danh's guidance here's my solution
- (IBAction)emailButton:(id)sender {
NSArray *toRecipents = [NSArray arrayWithObject:#"reflex#ilovetheory.com"];
MFMailComposeViewController *mailer = [[MFMailComposeViewController alloc] init];
mailer.mailComposeDelegate = self;
[mailer setSubject:#"CSV File"];
[mailer setToRecipients:toRecipents];
NSArray *filenames = [self filesNamesStartingAt:[NSDate date] count:165];
[self attachFilesNamed:filenames toMailer:mailer];
[self presentModalViewController:mailer animated:YES];
}
// answer count strings, named for days starting at date and the count-1 following days
- (NSArray *)filesNamesStartingAt:(NSDate *)date count:(NSInteger)count {
NSMutableArray *result = [NSMutableArray array];
static NSDateFormatter *dateFormat;
if (!dateFormat) {
dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"MM-dd-yyyy"];
}
for (int i=0; i<count; ++i) {
NSString *dateString = [dateFormat stringFromDate:date];
NSString *path = [[self applicationDocumentsDirectory].path
stringByAppendingPathComponent:[NSString stringWithFormat:#"_SurveyData_%#.csv",dateString]];
[result addObject:path];
date = [self addDayToDate:date];
}
for (int i=0; i<count; ++i) {
NSString *dateString = [dateFormat stringFromDate:date];
NSString *path = [[self applicationDocumentsDirectory].path
stringByAppendingPathComponent:[NSString stringWithFormat:#"_SurveyData_%#.csv",dateString]];
[result addObject:path];
date = [self subDayToDate:date];
}
return result;
}
// answer a new date, advanced one day from the passed date
- (NSDate *)addDayToDate:(NSDate *)date {
NSDateComponents *components = [[NSDateComponents alloc] init];
[components setDay:1];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
return [gregorian dateByAddingComponents:components toDate:date options:0];
}
- (NSDate *)subDayToDate:(NSDate *)date {
NSDateComponents *components = [[NSDateComponents alloc] init];
[components setDay:-1];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
return [gregorian dateByAddingComponents:components toDate:date options:0];
}
- (void)attachFilesNamed:(NSArray *)paths toMailer:(MFMailComposeViewController *)mailer {
for (NSString *path in paths) {
if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
NSData *data = [NSData dataWithContentsOfFile:path];
[mailer addAttachmentData:data mimeType:#"text/csv" fileName:path];
} else {
NSLog(#"warning, no file at path %#", path);
}
}
}
- (NSURL *)applicationDocumentsDirectory {
return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory
inDomains:NSUserDomainMask] lastObject];
}
It does look like you're very close. Maybe decomposing the problem a little more is what's needed:
Start with a method that will create the file names for several days starting at a given day...
// answer count strings, named for days starting at date and the count-1 following days
- (NSArray *)filesNamesStartingAt:(NSDate *)date count:(NSInteger)count {
NSMutableArray *result = [NSMutableArray array];
static NSDateFormatter *dateFormat;
if (!dateFormat) {
dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"MM-dd-yyyy"];
}
for (int i=0; i<count; ++i) {
NSString *dateString = [dateFormat stringFromDate:date];
NSString *path = [[self applicationDocumentsDirectory].path
stringByAppendingPathComponent:[NSString stringWithFormat:#"_SurveyData_%#.csv",dateString]];
[result addObject:path];
date = [self addDayToDate:date];
}
return result;
}
// answer a new date, advanced one day from the passed date
- (NSDate *)addDayToDate:(NSDate *)date {
NSDateComponents *components = [[NSDateComponents alloc] init];
[components setDay:1];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
return [gregorian dateByAddingComponents:components toDate:date options:0];
}
Now, add a method that will attach a set of named files to a mail controller:
- (void)attachFilesNamed:(NSArray *)paths toMailer:(MFMailComposeViewController *)mailer {
for (NSString *path in paths) {
if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
NSData *data = [NSData dataWithContentsOfFile:path];
[mailer addAttachmentData:data mimeType:#"text/csv" fileName:path];
} else {
NSLog(#"warning, no file at path %#", path);
}
}
}
The rest practically writes itself (I hope)...
MFMailComposeViewController *mailer = [[MFMailComposeViewController alloc] init];
mailer.mailComposeDelegate = self;
[mailer setSubject:#"CSV File"];
[mailer setToRecipients:toRecipents];
NSArray *filenames = [self fileNamesStartingAt:[NSDate date] count:3];
[self attachFilesNamed:filenames toMailer:mailer];
Note that, as written, this will use today and the next two days for filenames. If this isn't your requirement, you can tweak the addDay method to create a subtract days method, then work with those in tandem.
You're creating a filepath, but in the [mailer addAttachmentData] call, you're not passing in that path as I assume you intended--instead it's just getting the string that you used to build the path, so your NSData is going to be nil because it's not a complete path to anything on disk. Try changing that line to [mailer addAttachmentData:[NSData dataWithContentsOfFile:path]]

NSFetchedResultsController: ReOrder Sections

I'm following the example from Apple to setup my sections:
https://developer.apple.com/library/ios/samplecode/DateSectionTitles/Listings/DateSectionTitles_APLEvent_m.html
My sections currently appear in the following order:
Section 0: "Upcoming"
Section 1: "Today"
Section 2: "Past"
Code I use in my NSManagedObject .m file:
#pragma mark - Transient properties
- (NSString *)sectionIdentifier
{
// Create and cache the section identifier on demand.
[self willAccessValueForKey:#"sectionIdentifier"];
NSString *tmp = [self primitiveSectionIdentifier];
[self didAccessValueForKey:#"sectionIdentifier"];
if (!tmp)
{
NSDate *dateToCompare = [self getUTCFormateDate:[self startDate]];
NSLog(#"********Date To Compare****** %#", dateToCompare);
NSCalendar* calendar = [NSCalendar currentCalendar];
NSDate* now = [NSDate date];
NSDateFormatter *format = [[NSDateFormatter alloc] init];
format.dateFormat = #"dd-MM-yyyy";
NSString *stringDate = [format stringFromDate:now];
NSDate *todaysDate = [format dateFromString:stringDate];
NSInteger differenceInDays =
[calendar ordinalityOfUnit:NSDayCalendarUnit inUnit:NSEraCalendarUnit forDate:dateToCompare] -
[calendar ordinalityOfUnit:NSDayCalendarUnit inUnit:NSEraCalendarUnit forDate:todaysDate];
NSString *sectionString;
if (differenceInDays == 0)
{
sectionString = kSectionIDToday;
}
else if (differenceInDays < 0)
{
sectionString = kSectionIDPast;
}
else if (differenceInDays > 0)
{
sectionString = kSectionIDUpcoming;
}
tmp = sectionString;
[self setPrimitiveSectionIdentifier:tmp];
}
return tmp;
}
-(NSDate *)getUTCFormateDate:(NSDate *)localDate
{
NSDateFormatter *dateFormatter;
if (!dateFormatter)
{
dateFormatter = [[NSDateFormatter alloc] init];
}
NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:#"UTC"];
[dateFormatter setTimeZone:timeZone];
[dateFormatter setDateFormat:#"yyyy-MM-dd"];
NSString *dateString = [dateFormatter stringFromDate:localDate];
NSDate *dateFromString = [[NSDate alloc] init];
dateFromString = [dateFormatter dateFromString:dateString];
return dateFromString;
}
#pragma mark - Time stamp setter
- (void)setStartDate:(NSDate *)newDate
{
// If the time stamp changes, the section identifier become invalid.
[self willChangeValueForKey:#"startDate"];
[self setPrimitiveStartDate:newDate];
[self didChangeValueForKey:#"startDate"];
[self setPrimitiveSectionIdentifier:nil];
}
#pragma mark - Key path dependencies
+ (NSSet *)keyPathsForValuesAffectingSectionIdentifier
{
// If the value of timeStamp changes, the section identifier may change as well.
return [NSSet setWithObject:#"startDate"];
}
In my tableViewController, I setup the NSFetchedResults as following:
- (NSFetchedResultsController *)fetchedResultsController
{
if(_fetchedResultsController!=nil)
{
return _fetchedResultsController;
}
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Entity"
inManagedObjectContext:self.managedObjectContext];
[fetchRequest setEntity:entity];
NSSortDescriptor *firstSort = [[NSSortDescriptor alloc] initWithKey:#"startDate"
ascending:NO];
NSArray *sortDescriptors = [[NSArray alloc]initWithObjects:firstSort,nil];
[fetchRequest setSortDescriptors:sortDescriptors];
self.fetchedResultsController = [[NSFetchedResultsController alloc]initWithFetchRequest:fetchRequest
managedObjectContext:self.managedObjectContext
sectionNameKeyPath:#"sectionIdentifier"
cacheName:nil];
self.fetchedResultsController.delegate = self;
return self.fetchedResultsController;
}
Question 1: How do I get the sections to appear in the following order:
Section 0: Today
Section 1: Upcoming
Section 2: Past
Question 2: Within each section, how do I sort the rows based on an attribute called "modified" in each object?
Both section and row ordering is 100% dependent upon the sort descriptors. You want your first sort descriptor to sort everything into the proper section and then your following sort descriptors will sort the rows within the sections.
For example, if you wanted three sections based off of "group" and then you wanted the rows sorted by name inside of the group you would add the sort descriptors as:
NSArray *descriptors = #[[NSSortDescriptor sortDescriptorWithKey:#"group" ascending:YES], [NSSortDescriptor sortDescriptorWithKey:#"name" ascending:YES]];
[fetchRequest setSortDescriptors:descriptors];
Your section key for your NSFetchedResultsController will also need to match your first NSSortDescriptor.

UITableView scroll to section that is closest to todays date

I have a tableview with a calendar it's appointments in it. Each day is a separate section.
You can see what I mean over here
Now I want that the tableview scrolls to the section of today or if there is no section for today to the closest one.
I know that I should use the following piece of code:
[tableView scrollToRowAtIndexPath:scrollIndexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
Now I have an NSMutableDictionary that contains my sorted Appointments/day. You can see the function below:
-(NSDictionary *)sortKalendar:(NSMutableArray *)appointments{
NSMutableDictionary *buffer = [[NSMutableDictionary alloc] init];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"dd-MM-yyyy"];
for (int i = 0; i < appointments.count; i++) {
Appointment *object = [appointments objectAtIndex:i];
NSString *date = [formatter stringFromDate:object.app_start];
if(!(date == NULL) ){
NSLog(#"date is %#",date);
if ([buffer objectForKey:date]) {
[(NSMutableArray *)[buffer objectForKey:date] addObject:object];
} else {
NSMutableArray *mutableArray = [[NSMutableArray alloc] initWithObjects:object, nil];
[buffer setObject:mutableArray forKey:date];
}
}
}
NSDictionary *result = [NSDictionary dictionaryWithDictionary:buffer];
return result;
}
My question is now, how can I find the correct NSIndexpath ?
Thanks in advance !
EDIT
At the moment I'm using the following. But something is still not right.
NSArray *keys = [dictAppointments allKeys];
NSLog(#"KEYS ARE %#",keys) ;
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"dd-MM-yyyy"];
NSArray *sortedArray = [keys sortedArrayUsingComparator:^(id obj1, id obj2) {
NSDate *date1 = [formatter dateFromString:obj1];
NSDate *date2 = [formatter dateFromString:obj2];
NSNumber *interval1 = [NSNumber numberWithDouble:[date1 timeIntervalSinceNow]];
NSNumber *interval2 = [NSNumber numberWithDouble:[date2 timeIntervalSinceNow]];
return (NSComparisonResult)[interval1 compare:interval2];
}];
NSLog(#"Sorted Array %#",sortedArray);
NSString *closestDateString = [sortedArray objectAtIndex:0];
NSLog(#"Closest date string is %#",closestDateString);
int section = [keys indexOfObject:closestDateString];
NSIndexPath *scrollIndexPath = [NSIndexPath indexPathForRow:0 inSection:section];
[tableView scrollToRowAtIndexPath:scrollIndexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
This gives me the following logs:
2014-01-07 13:28:42.420 Adsolut[9579:60b] KEYS ARE (
"03-12-2013",
"20-12-2013",
"17-12-2013",
"05-01-2014",
"21-12-2013",
"31-12-2013",
"04-01-2014",
"06-01-2014",
"16-01-2014",
"29-12-2013",
"03-01-2014",
"11-01-2014",
"18-12-2013",
"31-01-2014"
)
2014-01-07 13:28:42.437 Adsolut[9579:60b] Sorted Array (
"03-12-2013",
"17-12-2013",
"18-12-2013",
"20-12-2013",
"21-12-2013",
"29-12-2013",
"31-12-2013",
"03-01-2014",
"04-01-2014",
"05-01-2014",
"06-01-2014",
"11-01-2014",
"16-01-2014",
"31-01-2014"
)
You can sort the array using time interval between appointment date and current date,
NSArray *keys = [yourDictionary allKeys];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"dd-MM-yyyy"];
NSArray *sortedArray = [keys sortedArrayUsingComparator:^(id obj1, id obj2) {
NSDate *date1 = [formatter dateFromString:obj1];
NSDate *date2 = [formatter dateFromString:obj2];
NSNumber *interval1 = [NSNumber numberWithDouble:abs([date1 timeIntervalSinceNow])];
NSNumber *interval2 = [NSNumber numberWithDouble:abs([date2 timeIntervalSinceNow])];
return (NSComparisonResult)[interval1 compare:interval2];
}];
And the closest date by,
NSString *closestDateString = [sortedArray objectAtIndex:0];
And from that,
int section = [keys indexOfObject:closestDateString];
NSIndexPath *scrollIndexPath = [NSIndexPath indexPathForRow:0 inSection:section];
Get the list of dates (from your dictionary or one you already have). Sort it. Loop over it (indexOfObjectPassingTest:) to find the date >= today (or use a predicate to filter and then take the first item from the result and get the index).
You have a sorted date array, don't you? Let's say it as dateArray.
Get today date object: NSDate * today = [NSDate date];
Search for dateArray to the nearest date, get the index of nearest date.
NSDate * today = [NSDate date] ;
__block NSUInteger section = NSNotFound ;
__block NSTimeInterval timeInterval = NSTimeIntervalSince1970 ;
[dateArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
NSDate * date = obj ;
NSTimeInterval ti = [today timeIntervalSinceDate:date] ;
if (ti < 0)
ti = -ti ;
if (ti <= timeInterval) {
section = idx ;
timeInterval = ti ;
} else {
*stop = YES ;
}
}] ;
You know the section index now, let's say it as sectionIndex, the first row index in the section is 0.
So the NSIndexPath is [NSIndexPath indexPathForRow:0 inSection:sectionIndex]

Resources