2013-07-24 34 views
0

我是一名初学者,我试图将我的应用程序移至Core Data。我遵循Big Nerd Ranch第三版的书,但在那本书中,他们有一个商店类,它将所有商品放在商品类中。我的应用程序不同。我有一个任务类,任务与TableView控制器中声明的任务数组一起显示,如果点击任务,其详细信息将显示在Detail View Controller中。问题是,这本书说我需要创建一个NSManagedObjectContext,NSManagedObjectModel和一个NSPersistentStoreCoordinator,它们在商店中做。我在哪里可以在我的应用中声明这些内容? TableView控制器或Detail View Controller?这里是我的代码:与实施核心数据混淆

Tasks.h

#import <Foundation/Foundation.h> 
#import <CoreData/CoreData.h> 

@interface Tasks : NSManagedObject 

@property (nonatomic) NSDateComponents *conversionInfo; 
@property (nonatomic) NSTimeInterval dateCreated; 
@property (nonatomic) double orderingValue; 
@property (nonatomic, retain) NSString * taskName; 
@property (nonatomic) double timeInterval; 
@property (nonatomic, retain) NSString * timeIntervalString; 
@property (nonatomic, retain) NSManagedObject *assetType; 

@end 

Tasks.m

@implementation Tasks 

@dynamic conversionInfo; 
@dynamic dateCreated; 
@dynamic orderingValue; 
@dynamic taskName; 
@dynamic timeInterval; 
@dynamic timeIntervalString; 
@dynamic assetType; 

-(void)awakeFromFetch{ 
    [super awakeFromFetch]; 
} 
-(void)awakeFromInsert{ 
    [super awakeFromInsert]; 
    NSTimeInterval t = [[NSDate date] timeIntervalSinceReferenceDate]; 
    [self setDateCreated:t]; 
} 
-(NSString *)timeIntervalString{ 
    NSCalendar *sysCalendar = [NSCalendar currentCalendar]; 
    NSDate *date = [NSDate date]; 
    NSDate *date1 = [NSDate dateWithTimeInterval:self.timeInterval sinceDate:date]; 
    unsigned int unitFlags = NSHourCalendarUnit | NSMinuteCalendarUnit; 
    self.conversionInfo = [sysCalendar components:unitFlags fromDate:date toDate:date1 options:0]; 
    if ([self.conversionInfo hour] == 0){ 
     if ([self.conversionInfo minute] == 1) { 
      self.timeIntervalString = [NSString stringWithFormat:@"%d MIN", [self.conversionInfo minute]]; 
     } else { 
      self.timeIntervalString = [NSString stringWithFormat:@"%d MINS", [self.conversionInfo minute]]; 
     } 
    } else if ([self.conversionInfo hour] == 1) { 
     if ([self.conversionInfo minute] == 0){ 
      self.timeIntervalString = [NSString stringWithFormat:@"%d HR", [self.conversionInfo hour]]; 
     } else if ([self.conversionInfo minute] == 1) { 
      self.timeIntervalString = [NSString stringWithFormat:@"%d HR %d MIN", [self.conversionInfo hour], [self.conversionInfo minute]]; 
     } else { 
      self.timeIntervalString = [NSString stringWithFormat:@"%d HR %d MINS", [self.conversionInfo hour], [self.conversionInfo minute]]; 
     } 
    } else { 
     if ([self.conversionInfo minute] == 0) { 
      self.timeIntervalString = [NSString stringWithFormat:@"%d HRS ", [self.conversionInfo hour]]; 
     } else if ([self.conversionInfo minute] == 1){ 
      self.timeIntervalString = [NSString stringWithFormat:@"%d HRS %d MIN", [self.conversionInfo hour], [self.conversionInfo minute]]; 
     } else { 
      self.timeIntervalString = [NSString stringWithFormat:@"%d HRS %d MINS", [self.conversionInfo hour], [self.conversionInfo minute]]; 
     } 
    } 
    return self.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]; 
} 

详细查看Controller.m或者

@interface DetailViewController() 

@end 
@implementation DetailViewController 
@synthesize testTask,timer,timerLabel, date1, alertView, components, timeRemaining; 
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil 
{ 
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; 
    if (self) { 


    } 
    return self; 
} 

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    [_timeLeft setFont:[UIFont fontWithName:@"BebasNeue" size:25]]; 
    } 
-(IBAction)startTimer:(id)sender{ 
    [sender setHidden:YES]; 
    [pauseButton setHidden:NO]; 
    [continueButton setHidden:NO]; 
     gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; 
     self.date1 = [NSDate dateWithTimeInterval:[testTask timeInterval] sinceDate:[NSDate date]]; 

     timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerAction:) userInfo:nil repeats:YES]; 
    [timer fire]; 

} 
-(void)viewWillAppear:(BOOL)animated{ 
    [super viewWillAppear:animated]; 

    [timerLabel setFont:[UIFont fontWithName:@"BebasNeue" size:60]]; 
    [[self navigationItem] setTitle:[testTask taskName]]; 
    if (startButton.hidden == NO){ 
     [pauseButton setHidden:YES]; 
     [continueButton setHidden:YES]; 
    } else { 
     [pauseButton setHidden:NO]; 
     [continueButton setHidden:NO]; 
    } 
     timeRemaining = [NSString stringWithFormat:@"%02d:%02d:%02d", [components hour], [components minute], [components second]]; 
    timerLabel.text = timeRemaining; 
    [timerLabel setNeedsDisplay]; 
    [self.view setNeedsDisplay]; 
} 
-(void)viewWillDisappear:(BOOL)animated{ 
    [super viewWillDisappear:animated]; 

    [testTask setTaskName:[testTask taskName]]; 
    [testTask setTimeInterval:[testTask timeInterval]]; 

} 
-(void)timerAction:(NSTimer *)t{ 
    NSDate *now = [NSDate date]; 
    components = [gregorianCalendar components:NSHourCalendarUnit|NSMinuteCalendarUnit|NSSecondCalendarUnit fromDate:now toDate:self.date1 options:0]; 

    timeRemaining = nil; 
    if([now compare:self.date1] == NSOrderedAscending){ 
     timeRemaining = [NSString stringWithFormat:@"%02d:%02d:%02d", [components hour], [components minute], [components second]]; 
     NSLog(@"works %@", timeRemaining); 
    } else { 
     timeRemaining = [NSString stringWithFormat:@"00:00:00"]; 
     [self.timer invalidate]; 
     self.timer = nil; 
     if (self.alertView == NULL){ 
     self.alertView = [[UIAlertView alloc]initWithTitle:[testTask taskName] message:@"Time is up!" delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil]; 
     [alertView performSelectorOnMainThread:@selector(show) withObject:nil waitUntilDone:YES];  
     NSLog(@"ended"); 
     } 
    } 
    timerLabel.text = timeRemaining; 
    [timerLabel setNeedsDisplay]; 
    [self.view setNeedsDisplay]; 
} 
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex{ 
    self.alertView = NULL; 
} 

回答

0

您应在AppDelgate.h文件中声明NSManagedObjectContextNSManagedObjectModelNSPersistentStoreCoordinator

所有这三个对象大多只需要在应用程序中分配一次。
您需要整个应用程序需要NSManagedObjectContext才能保存/编辑/检索托管对象。我的建议: 创建一个新项目,选择Master- Detail Application模板。检查Use Core data选项。

您将获得关于此新应用程序的AppDelegate.hAppDelegate.m文件中核心数据的所有模板代码,您可以在应用程序中复制/粘贴该文件。

+0

,我会用[UIApplication的sharedApplication]委托]访问它们? – EvilAegis

+0

您希望在其他视图控制器中大部分时间使用NSManagedObjectContext对象,并且您可以在模板代码中看到它是AppDelegate.h中的一个属性。所以要获得它的引用,你必须通过使用AppDelegarte * appDelegate = [[UIApplication sharedApplication] delegate]来获得AppDelegate对象; 然后你想NSManagedObjectContext参考简单地做,appDelegate.managedObjectContext –

+0

虽然AppDelegate不是一个类... – EvilAegis

0

它们都是在appDelegate类中创建的。在创建项目时,选择核心数据选项和模型,并为您创建所有NSManagedObjectContext,NSManagedObjectModel和NSPersistentStoreCoordinator。他们是全球您可以通过使用访问它们的任何地方:


[[UIApplication sharedApplication]delegate]