2012-07-24 3 views
2

코어 데이터를 사용하는 iPhone 응용 프로그램을 만들고 싶습니다. 제가 이해 한대로, 마스터 디테일 애플리케이션 템플릿 만이 코어 데이터를 사용할 수있는 옵션을 제공합니다. 그러나 그것은 테이블 뷰를 생성합니다.마스터 세부 템플릿이없는 코어 데이터

내가 사용하고 싶은 것은 뷰 컨트롤러가 아닌 테이블 뷰 컨트롤러입니다. 단일보기 응용 프로그램 템플릿으로 코어 데이터를 사용할 수 없습니다.

이 문제를 해결하려면 어떤 방법을 따라야합니까?

감사합니다.

+0

여기 이름을 대체 새'의 UIViewController를로드하기위한'AppDelegate.m' 파일을 수정 '와 _violá_가 완료되었습니다. :) 또는 ... 당신은'CoreData'로 새로운 애플리케이션을 만들 수 있고'CoreData'의 관련 부분을'AppDelegate.m'와'AppDelegate.h'에서 당신의 다른 프로젝트로'CoreData'없이 원하는대로 복사 할 수 있습니다 'UIViewController','CoreData' 파일 추가, _violá_, 당신은 그것을 다시했습니다. :) – holex

+0

이미 많은 것을 구현 했으므로 내가 할 수 있다면 첫 번째 옵션이 좋을 것입니다. 나는 Appdelegate.m에서 무엇을 바꿔야 하는가? 감사합니다. – Ataman

+0

은'AppDelegate.m' 파일에'-saveContext','-managedObjectContext','-managedObjectModel','persistentStoreCoordinator'를 추가합니다. 이 파일에는'-applicationDocumentsDirectory' 메소드가 있습니다. 'NSManagedObjectContext','NSManagedObjectModel','NSManagedObjectModel'과'#import '에 대해'AppDelegate.h' 파일에 다음과 같은'readonly' 속성을 추가하고 응용 프로그램이' CoreData.framework'도 포함됩니다. – holex

답변

5

CoreData는 UITableView와 같은 UIKit 구성 요소에 바인딩되지 않는 프레임 워크라는 것을 알아야합니다. 어떤 종류의 응용 프로그램에서도 자유롭게 사용할 수 있습니다. CoreData 작업을 관리하고 CoreData.framework를 프로젝트에 추가하는 싱글 톤 클래스를 만드는 것뿐입니다.

#import <Foundation/Foundation.h> 
#import <CoreData/CoreData.h> 
@interface DataAccessLayer : NSObject 

@property (strong, nonatomic) NSManagedObjectContext *managedObjectContext; 
@property (strong, nonatomic) NSManagedObjectModel *managedObjectModel; 
@property (strong, nonatomic) NSPersistentStoreCoordinator *storeCoordinator; 

+ (DataAccessLayer *)sharedInstance; 
- (void)saveContext; 

@end 

DataAccessLayer.m

#import "DataAccessLayer.h" 
@interface DataAccessLayer() 
- (NSURL *)applicationDocumentsDirectory; 
@end 

@implementation DataAccessLayer 
@synthesize storeCoordinator; 
@synthesize managedObjectModel; 
@synthesize managedObjectContext; 

+ (DataAccessLayer *)sharedInstance { 
    __strong static DataAccessLayer *sharedInstance = nil; 
    static dispatch_once_t onceToken; 
    dispatch_once(&onceToken, ^{ 
    sharedInstance = [[DataAccessLayer alloc] init]; 
    sharedInstance.storeCoordinator = [sharedInstance persistentStoreCoordinator]; 
    sharedInstance.managedObjectContext = [sharedInstance managedObjectContext]; 
    }); 
    return sharedInstance; 
} 

#pragma mark - Core Data 

- (void)saveContext { 
    @synchronized(self) { 
    NSError *error = nil; 
    if (managedObjectContext != nil) 
    { 
     if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) 
     { 
     NSLog(@"error: %@", error.userInfo); 
     /* 
     Replace this implementation with code to handle the error appropriately. 

     abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. If it is not possible to recover from the error, display an alert panel that instructs the user to quit the application by pressing the Home button. 
     */ 
     NSLog(@"Unresolved error %@, %@", error, [error userInfo]); 
     UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Oops!" 
                 message:@"Something has gone terribly wrong! You need to reinstall the app in order for it to work properly." 
                 delegate:nil 
               cancelButtonTitle:@"Close." 
               otherButtonTitles:nil, nil]; 
     [alert show]; 
     } 
    } 
    } 
} 

#pragma mark Core Data stack 

/** 
Returns the managed object context for the application. 
If the context doesn't already exist, it is created and bound to the persistent store coordinator for the application. 
*/ 
- (NSManagedObjectContext *)managedObjectContext { 
    if (managedObjectContext != nil) 
    { 
    return managedObjectContext; 
    } 

    if (storeCoordinator != nil) 
    { 
    managedObjectContext = [[NSManagedObjectContext alloc] init]; 
    [managedObjectContext setPersistentStoreCoordinator:storeCoordinator]; 
    } 
    return managedObjectContext; 
} 

/** 
Returns the managed object model for the application. 
If the model doesn't already exist, it is created from the application's model. 
*/ 
- (NSManagedObjectModel *)managedObjectModel { 
    if (managedObjectModel != nil) 
    { 
    return managedObjectModel; 
    } 
    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"DataModel" withExtension:@"momd"]; 
    managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];  
    return managedObjectModel; 
} 

/** 
Returns the persistent store coordinator for the application. 
If the coordinator doesn't already exist, it is created and the application's store added to it. 
*/ 
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator { 
    if (storeCoordinator != nil) 
    { 
    return storeCoordinator; 
    } 

    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"words_db.sqlite"]; 

    NSError *error = nil; 
    storeCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]]; 
    if (![storeCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) 
    { 
    /* 
    Replace this implementation with code to handle the error appropriately. 

    abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. If it is not possible to recover from the error, display an alert panel that instructs the user to quit the application by pressing the Home button. 

    Typical reasons for an error here include: 
    * The persistent store is not accessible; 
    * The schema for the persistent store is incompatible with current managed object model. 
    Check the error message to determine what the actual problem was. 


    If the persistent store is not accessible, there is typically something wrong with the file path. Often, a file URL is pointing into the application's resources directory instead of a writeable directory. 

    If you encounter schema incompatibility errors during development, you can reduce their frequency by: 
    * Simply deleting the existing store: 
    [[NSFileManager defaultManager] removeItemAtURL:storeURL error:nil] 

    * Performing automatic lightweight migration by passing the following dictionary as the options parameter: 
    [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption, [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil]; 

    Lightweight migration will only work for a limited set of schema changes; consult "Core Data Model Versioning and Data Migration Programming Guide" for details. 

    */ 
    NSLog(@"Unresolved error %@, %@", error, [error userInfo]); 
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Oops!" 
                message:@"Something has gone terribly wrong! You need to reinstall the app in order for it to work properly." 
                delegate:nil 
              cancelButtonTitle:@"Close." 
              otherButtonTitles:nil, nil]; 
    [alert show]; 
    }  

    return storeCoordinator; 
} 

#pragma mark Application's Documents directory 

/** 
Returns the URL to the application's Documents directory. 
*/ 
- (NSURL *)applicationDocumentsDirectory { 
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject]; 
} 


@end 

당신은 또한 당신의 데이터를 만들기 위해에 .xcdatamodeld 파일을 만들어야합니다

DataAccessLayer.h : 여기

내 DataAccessLayer 템플릿입니다 모델 개체. 그리고 마지막으로, 번들에 새`UIViewController`를 추가하고, 단지 번들에서 불필요한 파일을 삭제 적절한

NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"DataModel" withExtension:@"momd"]; 
+0

당신이 말한대로 했어요. 그런 다음 모든 기존 코드를 새로 만든 앱에 복사합니다. 빌드 오류가 없습니다. 하지만 내가 그것을 실행하면 '+ entityForName : 엔티티 이름'UserData '에 대한 NSManagedObjectModel을 찾을 수 없다는 런타임 오류가 발생합니다.'UserData는 내 핵심 데이터의 내 엔티티 이름입니다. 왜 이런 일이 발생하는지 알고 있습니까? 감사! – Ataman

+0

내가 이전 응용 프로그램에서 수행했던 것은 동일한 클래스에서 managedobjectcontext를 작성하여 NSManagedObjectContext * context = [self managedObjectContext]를 사용하고있었습니다. 하지만 지금 우리가 datalayeraccess 클래스에서 그것을 생성하는 것 같아요, 대신 자체 managedobjectcontext 내가 뭔가 다른 것을 사용해야합니까? – Ataman

+0

마지막으로 해냈습니다. 가이드 주셔서 감사합니다 !! – Ataman