NSMutableDictonary为接下来7天的每一天的NSMutableArrays任务

时间:2016-02-05 05:59:34

标签: ios objective-c algorithm sorting nsmutabledictionary

我有一个应用程序,最终目标是允许用户输入他们的所有任务。有两种类型的任务:

•严格的任务 - 任务w。严格的开始时间
•随机任务 - 任务w。没有特定的开始时间

最终目标是应用程序将通过显示一周中接下来7天的分段表视图自动输出所有任务。该应用程序还需要适应"你的"随机任务"进入你的日程表中的空白。

到目前为止,我得到了:
•任务成功保存到SQLite中 •一个抓住"严格任务"按时间顺序(最快) •一种抓取所有"随机任务"的功能 •我认为这个功能可以成功排序并且适合"将所有给定的任务放入已排序的最终数组中。

我有点难过的是如何以理想的方式为分段的tableview输出任务(我猜测标准方式是通过NSMutableArrays的NSMutableDictionary为接下来的7天每一天),但我不知道是什么从上面的项目符号排序的最终数组到NSMutableArrays的NSMutableDictionary的最佳方法.Anyone有一个建议吗?如果我觉得这比你需要的更困难,请随意仔细检查我的任何步骤。

ModelSingleton Logic

#define WhereAmI NSLog((@"%s [Line %d] "), __PRETTY_FUNCTION__, __LINE__);


// NOTE: This is the singleton object that the class maintains to point and hand to everyone who wants an instance of this class.  It is 'static' meaning that only one can exist throughout all versions of this class (which this forces to be only one).
static ModelSingleton * sharedInstance = nil;


@implementation ModelSingleton

#pragma mark - Singleton & Class Methods
//NOTE: This is the method you use to grab the instance of this object.
+ (ModelSingleton *)sharedInstance
{
    //Static local predicate must be initialized to 0
    static ModelSingleton *sharedInstance = nil;
    static dispatch_once_t onceToken = 0;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[ModelSingleton alloc] init];
        // Do any other initialisation stuff here



    });
    return sharedInstance;
}


-(NSString *)getDBPath{


    NSString *DB_PATH = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString * path = [DB_PATH stringByAppendingPathComponent:@"tasks.sqlite"];

    return path;
}

-(void)createDatabase{


    _db_path=[self getDBPath];

    NSFileManager * fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:_db_path] == NO) {
        // create it
        FMDatabase * db = [FMDatabase databaseWithPath:_db_path];
        if ([db open]) {
            NSString * sql = @"CREATE TABLE 'Tasks' ('TASK_ID' INTEGER PRIMARY KEY AUTOINCREMENT  NOT NULL , 'TASK_NAME' VARCHAR(100), 'TASK_DURRATION' INTEGER,'TASK_START_TSTAMP' INTEGER)";
            BOOL res = [db executeUpdate:sql];
            if (!res) {
                NSLog(@"error when creating db table");
            } else {
                NSLog(@"succ to creating db table");
            }
            [db close];
        } else {
            NSLog(@"error when open db");
        }
    }else{

        [self deleteDBFile];
        NSLog(@"The file already exists");
    }
}

- (void)insertNewTask:(NSString *)taskName withDurration:(int)durration andStrictStartTime:(int)start_time {

    NSLog(@"FROM_MODEL_TASK_NAME:%@",taskName);
    NSLog(@"FROM_MODEL_TASK_DURRATION:%d",durration);
    NSLog(@"FROM_MODEL_TASK_START_TIME:%d",start_time);

    _db_path=[self getDBPath];
    NSLog(@"SQLITE_PATH:%@",_db_path);
    FMDatabase * db = [FMDatabase databaseWithPath:_db_path];
    if ([db open]) {

        BOOL res = [db executeUpdate:@"insert into Tasks (TASK_NAME,TASK_DURRATION,TASK_START_TSTAMP) values(?,?,?)", taskName,[NSNumber numberWithInt:durration],[NSNumber numberWithInt:start_time]];
        if (!res) {
            NSLog(@"error to insert data");
        } else {
            NSLog(@"succ to insert data");
        }
        [db close];
    }
}

-(void)clearDB{
    FMDatabase * db = [FMDatabase databaseWithPath:   _db_path=[self getDBPath]];
    if ([db open]) {
        NSString * sql = @"DELETE FROM Tasks";
        BOOL res = [db executeUpdate:sql];
        if (!res) {
            NSLog(@"error to delete db data");
        } else {
            NSLog(@"succ to delete db data");
        }
        [db close];
    }



}
-(NSMutableArray *)getTasksInTimestampOrder{
    [_tasksArray removeAllObjects];
    NSMutableArray *tasksArray = [[NSMutableArray alloc]init];
    int CurrentTStamp=[[NSDate date] timeIntervalSince1970];
    NSMutableDictionary *task = [[NSMutableDictionary alloc]init];

    [task setValue:@"Now" forKey:@"TASK_NAME"];
    [task setValue:[NSNumber numberWithInt:CurrentTStamp] forKey:@"TASK_START_TIME"];
    [task setValue:[NSNumber numberWithInt:1] forKey:@"TASK_DURRATION"];
    [tasksArray addObject:task];


    FMDatabase * db = [FMDatabase databaseWithPath:[self getDBPath]];
    if ([db open]) {
        NSString * sql = @"SELECT * from Tasks WHERE TASK_START_TSTAMP<>0 ORDER BY TASK_START_TSTAMP ASC";
        FMResultSet * rs = [db executeQuery:sql];
        while ([rs next]) {
            int START_TSTAMP = [rs intForColumn:@"TASK_START_TSTAMP"];

            NSString *day=[self getDayofTheWeek:START_TSTAMP];


            int TASK_DURRATION = [rs intForColumn:@"TASK_DURRATION"];
            NSString * name = [rs stringForColumn:@"TASK_NAME"];
            NSLog(@"TASK_NAME:%@ | TASK_TSTAMP:%d", name, START_TSTAMP);

            NSMutableDictionary *task = [[NSMutableDictionary alloc]init];
            [task setObject:day forKey:@"DAY_OF_WEEK"];
            [task setValue:name forKey:@"TASK_NAME"];
            [task setValue:[NSNumber numberWithInt:START_TSTAMP] forKey:@"TASK_START_TIME"];
            [task setValue:[NSNumber numberWithInt:TASK_DURRATION] forKey:@"TASK_DURRATION"];
            [tasksArray addObject:task];



        }

        NSLog(@"TASKS_ARRAY:%@",tasksArray);
        [db close];
        if(tasksArray!=nil){
            return tasksArray;
        }

    }

    return nil;

}


-(NSMutableArray *)getRandomTasks{
    [_tasksArray removeAllObjects];
    NSMutableArray *tasksArray = [[NSMutableArray alloc]init];



    FMDatabase * db = [FMDatabase databaseWithPath:[self getDBPath]];
    if ([db open]) {
        NSString * sql = @"SELECT * from Tasks WHERE TASK_START_TSTAMP=0";
        FMResultSet * rs = [db executeQuery:sql];
        while ([rs next]) {
            int START_TSTAMP = [rs intForColumn:@"TASK_START_TSTAMP"];
            int TASK_DURRATION = [rs intForColumn:@"TASK_DURRATION"];
            NSString * name = [rs stringForColumn:@"TASK_NAME"];
            NSLog(@"TASK_NAME:%@ | TASK_TSTAMP:%d", name, START_TSTAMP);

            NSMutableDictionary *task = [[NSMutableDictionary alloc]init];

            [task setValue:name forKey:@"TASK_NAME"];
            [task setValue:[NSNumber numberWithInt:START_TSTAMP] forKey:@"TASK_START_TIME"];
            [task setValue:[NSNumber numberWithInt:TASK_DURRATION] forKey:@"TASK_DURRATION"];
            [tasksArray addObject:task];


        }

        [db close];
        NSLog(@"TASKS_ARRAY:%@",tasksArray);

        if(tasksArray!=nil){
            return tasksArray;
        }
        return nil;

    }

    return nil;


}


-(void)getAndSortAllTasks{




    NSMutableArray *timeOrderedTasksArray=[self getTasksInTimestampOrder];
    NSMutableArray *finalSortedArray=[timeOrderedTasksArray mutableCopy];
    NSMutableArray *randomTasksArray=[self getRandomTasks];
    if(timeOrderedTasksArray!=nil){

        int i;
        for(i = 0;i ==timeOrderedTasksArray.count;i = i + 1)
        {

            NSMutableDictionary *currentTask=[timeOrderedTasksArray objectAtIndex:i];
            int currentTaskTimeStamp = [[currentTask objectForKey:@"TASK_START_TIME"] intValue];
            int taskDurration = [[currentTask objectForKey:@"TASK_DURRATION"] intValue];
            int taskEndTimestamp =currentTaskTimeStamp+taskDurration;

            if(i+1>=timeOrderedTasksArray.count){
                if(randomTasksArray!=nil){
                    NSMutableDictionary *nextTask=[timeOrderedTasksArray objectAtIndex:i+1];
                    int nextTaskTimeStamp = [[nextTask objectForKey:@"TASK_START_TIME"] intValue];


                    int timeLeftBetweenTasks= nextTaskTimeStamp-taskEndTimestamp;

                    NSMutableArray *updatedRandomTasks=[randomTasksArray mutableCopy];
                    int r;
                    for(r = 0;r ==randomTasksArray.count;r = r + 1){
                        NSMutableDictionary *task=[randomTasksArray objectAtIndex:i];

                        int randomTaskDurration =[[task objectForKey:@"TASK_DURRATION"] intValue];
                        if(timeLeftBetweenTasks<randomTaskDurration){


                            [finalSortedArray insertObject:task atIndex:i+1];
                            [updatedRandomTasks removeObjectAtIndex:r];
                            timeLeftBetweenTasks=timeLeftBetweenTasks+randomTaskDurration;

                        }




                    }


                }


            }else{

                if(randomTasksArray!=nil){
                    for (NSDictionary *task in randomTasksArray){


                        [finalSortedArray addObject:task];


                    }

                }




            }


        }

    }
    NSLog(@"FINAL_SORTED_ARRAY:%@",finalSortedArray);

}


-(NSString *)getDayofTheWeek:(int)timestamp{

    NSDate *date = [NSDate dateWithTimeIntervalSince1970:timestamp];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.dateFormat = @"yyyyMMdd";



    dateFormatter.dateFormat=@"MMMM";
    NSString * monthString = [[dateFormatter stringFromDate:date] capitalizedString];
    NSLog(@"month: %@", monthString);

    dateFormatter.dateFormat=@"EEEE";
    NSString * dayString = [[dateFormatter stringFromDate:date] capitalizedString];
    NSLog(@"day: %@", dayString);

    return dayString;
}

- (void)deleteDBFile{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *filePath = [self getDBPath];
    NSError *error;
    BOOL success = [fileManager removeItemAtPath:filePath error:&error];
    if (success) {

         [self createDatabase];

    }
    else
    {
        UIAlertView *removeSuccessFulAlert=[[UIAlertView alloc]initWithTitle:@"Error:" message:@"Failed to Delete & Recreate DB" delegate:self cancelButtonTitle:@"Close" otherButtonTitles:nil];
        [removeSuccessFulAlert show];
    }
}


- (NSDate *)dateByAddingOneDayFromDate:(NSDate *)date {
    NSCalendar *cal = [NSCalendar currentCalendar];

    NSDateComponents *plusOneDay = [[NSDateComponents alloc] init];
    [plusOneDay setDay:+1];
    NSDate *newDate = [cal dateByAddingComponents:plusOneDay
                                           toDate:date
                                          options:NSWrapCalendarComponents];
    return newDate;
}

- (NSMutableDictionary *)lastSevenDays {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"EEEE"];

    NSDate *date = [NSDate date];
    NSMutableDictionary *weekDays = [[NSMutableDictionary alloc] init];
    for (int i = 0; i <7; i++) {
        NSString *weekDay = [formatter stringFromDate:date];

        NSMutableArray *dayArray=[[NSMutableArray alloc]init];
        [weekDays setObject:dayArray forKey:weekDay];
        date = [self dateByAddingOneDayFromDate:date];
    }
    return weekDays;
}

@end

enter image description here

0 个答案:

没有答案