2013-07-15 11 views
1

Я новичок в программировании на iOS, и это первое приложение, которое я когда-либо делал. В основном я не знал о основных данных при создании этого приложения, поэтому я делал классы нормально. Мое приложение в основном представляет собой приложение списка дел с задачами как объекты, которые вводят taskArray (массив, который действует как источник данных для TableViewController). Задачи вводятся в taskArray пользователями. У меня только один вопрос при переносе с объектов, которые стираются, когда приложение закрывается для основных данных. Должен ли я удалить класс Task и переделать его как объект в Core Data? Если это так, можно ли добавить объекты, которые я создаю с помощью Core Data, в taskArray или мне нужно полностью переделать все мое приложение и cellForRowAtIndexPath?Как перейти от экземпляров к основным данным?

Вот некоторые из моего кода:

Tasks.h

@interface Tasks : NSObject <NSCoding>{ 
    NSDateComponents *conversionInfo; 
} 
@property (strong, nonatomic) NSString *taskName; 
@property NSTimeInterval timeInterval; 
@property NSDate *dateCreated; 
@property (nonatomic) NSTimeInterval timeIntervalInMinutes; 
@property (nonatomic) NSTimeInterval timeIntervalInHours; 
@property (nonatomic) NSString *timeIntervalString; 
@end 

Tasks.m

@implementation Tasks 
@synthesize taskName, timeInterval, dateCreated; 
-(id) init{ 
    if (self) 
    { 
    self.taskName = taskName; 
    self.timeInterval = timeInterval; 
     self.dateCreated = dateCreated; 
    } 
    return self; 
} 
-(NSString *)timeIntervalString{ 
    NSCalendar *sysCalendar = [NSCalendar currentCalendar]; 
    NSDate *date = [NSDate date]; 
    NSDate *date1 = [NSDate dateWithTimeInterval:timeInterval sinceDate:date]; 
    unsigned int unitFlags = NSHourCalendarUnit | NSMinuteCalendarUnit; 
    conversionInfo = [sysCalendar components:unitFlags fromDate:date toDate:date1 options:0]; 
    if ([conversionInfo hour] == 0){ 
     if ([conversionInfo minute] == 1) { 
      _timeIntervalString = [NSString stringWithFormat:@"%d MIN", [conversionInfo minute]]; 
     } else { 
      _timeIntervalString = [NSString stringWithFormat:@"%d MINS", [conversionInfo minute]]; 
     } 
    } else if ([conversionInfo hour] == 1) { 
     if ([conversionInfo minute] == 0){ 
     _timeIntervalString = [NSString stringWithFormat:@"%d HR", [conversionInfo hour]]; 
    } else if ([conversionInfo minute] == 1) { 
    _timeIntervalString = [NSString stringWithFormat:@"%d HR %d MIN", [conversionInfo hour], [conversionInfo minute]]; 
    } else { 
    _timeIntervalString = [NSString stringWithFormat:@"%d HR %d MINS", [conversionInfo hour], [conversionInfo minute]]; 
    } 
    } else { 
     if ([conversionInfo minute] == 0) { 
     _timeIntervalString = [NSString stringWithFormat:@"%d HRS ", [conversionInfo hour]]; 
     } else if ([conversionInfo minute] == 1){ 
      _timeIntervalString = [NSString stringWithFormat:@"%d HRS %d MIN", [conversionInfo hour], [conversionInfo minute]]; 
     } else { 
     _timeIntervalString = [NSString stringWithFormat:@"%d HRS %d MINS", [conversionInfo hour], [conversionInfo minute]]; 
     } 
    } 
    return _timeIntervalString; 
} 
@end 

TableViewController.m

-(NSMutableArray *)taskArray { 
    if (!taskArray) { 
     taskArray = [NSMutableArray array]; 
    } 
    return taskArray; 
} 
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ 
cellSubclassCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewCell"]; 
    if (!cell) 
     cell = [[cellSubclassCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"UITableViewCell"]; 

    if([indexPath section] == 0){ 
    cell.textLabel.text = [[[self.taskArray objectAtIndex:[indexPath row]] taskName] uppercaseString]; 

    cell.imageView.image = [UIImage imageNamed:@"unchecked.png"]; 
     cell.imageView.highlightedImage = [UIImage imageNamed:@"uncheckedhighlighted.png"]; 
     [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator]; 
     [cell setBackgroundColor:[UIColor colorWithRed:236.0/255 green:240.0/255 blue:241.0/255 alpha:1.0f]]; 
     cell.textLabel.textColor = baseColor; 

     NSString *detailText = [[self.taskArray objectAtIndex:[indexPath row]] timeIntervalString]; 
     cell.detailTextLabel.text = detailText; 
       [[cell detailTextLabel] setFont:[UIFont fontWithName:@"Avenir-Black" size:12]]; 
     [[cell textLabel] setFont:[UIFont fontWithName:@"AvenirNext-DemiBold" size:16]]; 
[cell.contentView setAlpha:1]; 
    } else if ([indexPath section] == 1) { 
    cell.textLabel.text = [[[self.completedArray objectAtIndex:[indexPath row]] taskName] uppercaseString]; 

    cell.imageView.image = [UIImage imageNamed:@"checked.png"]; 
     [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator]; 
     [cell setBackgroundColor:[UIColor colorWithRed:236.0/255 green:240.0/255 blue:241.0/255 alpha:1.0f]]; 
     cell.textLabel.textColor = baseColor; 
     NSString *detailText = [[self.completedArray objectAtIndex:[indexPath row]] timeIntervalString]; 
     cell.detailTextLabel.text = detailText; 
     [[cell detailTextLabel] setFont:[UIFont fontWithName:@"Avenir-Black" size:12]]; 
     [[cell textLabel] setFont:[UIFont fontWithName:@"AvenirNext-DemiBold" size:16]]; 
     [cell.contentView setAlpha:0.5]; 
    } 
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(handlechecking:)]; 
    //cell.contentView 
    [cell.imageView addGestureRecognizer:tap]; 
    cell.imageView.userInteractionEnabled = YES; 
    return cell; 
    } 
    -(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{ 
    Tasks *task = [[Tasks alloc]init]; 
    if (indexPath.section == 0){ 
    task.taskName = [[self.taskArray objectAtIndex:[indexPath row]] taskName]; 
     task.timeInterval = [[self.taskArray objectAtIndex:[indexPath row]] timeInterval]; 
    task.dateCreated = [[self.taskArray objectAtIndex:[indexPath row]] dateCreated]; 
    } else if (indexPath.section == 1){ 
     task.taskName = [[self.completedArray objectAtIndex:[indexPath row]] taskName]; 
     task.timeInterval = [[self.completedArray objectAtIndex:[indexPath row]] timeInterval]; 
     task.dateCreated = [[self.completedArray objectAtIndex:[indexPath row]] dateCreated]; 
    } 
    DetailViewController *dvc = [[DetailViewController alloc]init]; 
    [dvc setTestTask:task]; 
    [[self navigationController] pushViewController:dvc animated:YES]; 
} 

ответ

1

Должен ли я удалить класс Task и переделать его как объект в Core Data?

Это может быть проще изменить Task так, что это подкласс NSManagedObject, создать свою модель и установить Task как класс для объекта задачи в вашей модели. Вам все равно придется выполнить какую-то работу по преобразованию приложения в Core Data, но любая логика, которую вы создали для своего класса задач, по-прежнему может быть полезна.

0

Будучи новичком, я также рекомендую вам ознакомиться с базовыми структурами данных Core, такими как разумная система TableView. Экономит меня за время разработки при работе с Core Data.

Смежные вопросы