2012-04-19 8 views

Odpowiedz

11

Xcode 4.3.2 Aby dodać szkielet danych podstawowych.

Wybierz Cel-> Panel podsumowań-> Powiązane struktury & Biblioteki.

enter image description here

W powyższym zdjęciu CoreData Framework jest już dodany. U można kliknąć przycisk "+" poniżej, aby dodać ramy wyboru.

RAZ U KICK ON "+" PRZYCISK UÜLL PONIŻEJ OBRAZU EKRAN.

enter image description here

Aby dodać nowe pliki do niego iść do Plik-> Nowy plik -> iOS Tab-> CoreData setion.You może złożyć ur wyboru

enter image description here

+1

Ponadto można zmienić styl Editor do widoku graficznym następnie można dodać podmiotu przez naciśnięcie (+ Dodaj podmiot) znak. Również do generowania właściwej podklasy NSManagedObject dla tej konkretnej jednostki, wybierz tę jednostkę, a następnie wybierz opcję "Editor" w XCode -> Utwórz NSManagedObject Subclass ..., utworzy odpowiedni plik .h & .m dla tego obiektu. – raaz

+0

@raaz Tak, zgadzam się.! –

9

Dodaj CoreData ramy projektu, a następnie utwórz plik .xdatamodeld (Plik-> Nowy-> CoreData-> Model danych). Nazwij go DataModel. Następnie należy utworzyć klasę singleton, która będzie obsługiwać wszystkie dane wytrwałości operacje:

.h

// 
    // DataAccessLayer.h 
    // 
    // 
    // Copyright (c) 2012 __MyCompanyName__. All rights reserved. 
    // 

    #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 

.m

// 
// DataAccessLayer.m 
// 
// 
// Created by admin on 2/27/12. 
// Copyright (c) 2012 __MyCompanyName__. All rights reserved. 
// 

#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 { 
    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) 
    { 
    self.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"]; 
    self.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:@"model.sqlite"]; 

    NSError *error = nil; 
    self.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 
+0

najpiękniejszy! Jestem nowy dla ios i właśnie przebiegłem przez większość mojego dnia, próbując implementować błędy danych w kółko w delegacie aplikacji, zdobywając kontekst, przekazując go kontrolerom widoku, ugh! To jest słodkie i działa idealnie! – farcrats

+0

O wiele lepsze niż umieszczanie kodu w Delegacie aplikacji! – zaph

3

Zarówno hp iOS Coder 's i Eugene' s odpowiedzi są poprawne!

plik

Core danych (lub projekt) jest skonfigurowany do:

  1. link do i obejmują ramy podstawowe dane (a nie tak jak w instrukcji import w projekcie za .pch pliku)
  2. app delegata nagłówek (.h) ma właściwości deklarujàcych context, model i coordinator (jak wyżej)
  3. .m app delegate jest definiuje saveContext, managedObjectContext, managedObjectModel, persistentStoreCoordinator, applicationDocumentDirectory funkcje/metody
  4. model danych, jak powyżej
Powiązane problemy