Dodawanie podstawowych danych do istniejącego projektu iPhone ' a

Chciałbym dodać core data do istniejącego projektu iPhone ' a, ale wciąż dostaję dużo błędów kompilacji:

- NSManagedObjectContext undeclared

 - Expected specifier-qualifier-list before 'NSManagedObjectModel'

 - ...

Dodałem już ramkę Core Data do celu (kliknij prawym przyciskiem myszy Mój projekt pod "cele", "Dodaj" - "istniejące ramy", " CoreData.framework").

Mój plik nagłówka:

NSManagedObjectModel *managedObjectModel;
NSManagedObjectContext *managedObjectContext;       
NSPersistentStoreCoordinator *persistentStoreCoordinator;

[...]

@property (nonatomic, retain, readonly) NSManagedObjectModel *managedObjectModel;
@property (nonatomic, retain, readonly) NSManagedObjectContext *managedObjectContext;
@property (nonatomic, retain, readonly) NSPersistentStoreCoordinator *persistentStoreCoordinator;
Co mi umyka? Rozpoczęcie nowego projektu nie wchodzi w grę...

Wielkie dzięki!

Edit przepraszam, ale mam te implementacje... ale wydaje się, że Biblioteka zaginęła... metody implementacji są pełne z błędem kompilacji jak "managedObjectContext undeclared", "NSPersistentStoreCoordinator undeclared", ale także z "Expected') 'przed NSManagedObjectContext" (choć wydaje się, że nawias jest poprawny)...

#pragma mark -
#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;
    }

    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (coordinator != nil) {
        managedObjectContext = [[NSManagedObjectContext alloc] init];
        [managedObjectContext setPersistentStoreCoordinator: coordinator];
    }
    return managedObjectContext;
}


/**
 Returns the managed object model for the application.
 If the model doesn't already exist, it is created by merging all of the models found in    
 application bundle.
 */
- (NSManagedObjectModel *)managedObjectModel {

    if (managedObjectModel != nil) {
        return managedObjectModel;
    }
    managedObjectModel = [[NSManagedObjectModel mergedModelFromBundles:nil] retain];    
    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 (persistentStoreCoordinator != nil) {
        return persistentStoreCoordinator;
    }

    NSURL *storeUrl = [NSURL fileURLWithPath: [[self applicationDocumentsDirectory] 
        stringByAppendingPathComponent: @"Core_Data.sqlite"]];

    NSError *error = nil;
    persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] 
    initWithManagedObjectModel:[self managedObjectModel]];
    if (![persistentStoreCoordinator 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.
     */
    NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
    abort();
}    

return persistentStoreCoordinator;
}
 135
Author: nhgrif, 2010-01-09

13 answers

Wszystkie pliki nagłówkowe CoreData są importowane w App_Prefix.pch , więc klasy CoreData będą dostępne w całym projekcie, więc nie musisz ręcznie importować nagłówka do potrzebnych plików.

Więc otwórz Xcode i poszukaj jakiegoś pliku typu App_Prefix.pch, domyślnie jest on w grupie Other Sources. Po instrukcji importUIKit Dodaj następujący wiersz:

#import <CoreData/CoreData.h>
I powinieneś być gotowy do drogi.

Xcode 4

Dla projektów utworzonych w Xcode 4, Plik prefiksu może być Znalezione w grupie Supporting Files w Nawigatorze projektu. Nazywa się ' projectname -prefiks.PCH ' domyślnie.

Xcode 6 +

Począwszy od Xcode 6, wstępnie skompilowany plik nagłówka nie jest domyślnie dołączany. Jest to spowodowane wprowadzeniem modułów, które eliminują potrzebę używania wstępnie skompilowanych nagłówków. chociaż nadal można ręcznie dodać plik PCH, aby globalnie zawierał nagłówki CoreData, rozważ określenie zależności CoreData za pomocą @import CoreData;* w każdy plik, który używa CoreData. Sprawia to, że zależności są jednoznaczne i co ważniejsze, unikną problemu tego pytania w przyszłości.

* Moduły muszą być włączone aby to działało.

 145
Author: Joost,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 11:33:26

Aby wyjaśnić wszystkie kroki, które musisz wykonać, aby dodać podstawowe dane do projektu, który wcześniej ich nie posiadał:

Krok 1: Dodaj Framework

Kliknij na docelowej aplikacji (na lewym panelu jest to górna ikona z nazwą aplikacji) następnie przejdź do zakładki "Build faz" następnie na "Link Binary z bibliotekami", kliknij mały " + "na dole, a następnie znaleźć" CoreData.framework ' i dodaj go do swojego projektu

Następnie Importuj coredata na wszystkich obiektach potrzebujesz go (nie-sexy sposób) za pomocą:

Swift

import CoreData

Objective C

#import <CoreData/CoreData.h>

Lub dodać import pod wspólnym importem w Twoim .plik pch (o wiele bardziej seksowny) jak ten:

#ifdef __OBJC__
    #import <UIKit/UIKit.h>
    #import <Foundation/Foundation.h>
    #import <CoreData/CoreData.h>
#endif

Krok 2: Dodaj model danych

Aby dodać .plik XCDATAMODEL kliknij prawym przyciskiem myszy / control-kliknij pliki w prawym okienku (jak w folderze zasobów do przechowywania) i wybierz, aby dodać nowy plik, kliknij kartę Podstawowe dane podczas wybierania typu pliku następnie kliknij "model danych", nadaj mu nazwę i kliknij Dalej i Zakończ, a on doda go do twojego projektu. Po kliknięciu na ten obiekt modelu zobaczysz interfejs, aby dodać encje do projektu z dowolnymi relacjami, które chcesz.

Krok 3: Zaktualizuj Delegata Aplikacji

In Swift on AppDelegate.swift

//replace the previous version of applicationWillTerminate with this
func applicationWillTerminate(application: UIApplication) {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    // Saves changes in the application's managed object context before the application terminates.
    self.saveContext()
}

func saveContext () {
    var error: NSError? = nil
    let managedObjectContext = self.managedObjectContext
    if managedObjectContext != nil {
        if managedObjectContext.hasChanges && !managedObjectContext.save(&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.
            //println("Unresolved error \(error), \(error.userInfo)")
            abort()
        }
    }
}

// #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.
var managedObjectContext: NSManagedObjectContext {
    if !_managedObjectContext {
        let coordinator = self.persistentStoreCoordinator
        if coordinator != nil {
            _managedObjectContext = NSManagedObjectContext()
            _managedObjectContext!.persistentStoreCoordinator = coordinator
        }
    }
    return _managedObjectContext!
}
var _managedObjectContext: NSManagedObjectContext? = nil

// Returns the managed object model for the application.
// If the model doesn't already exist, it is created from the application's model.
var managedObjectModel: NSManagedObjectModel {
    if !_managedObjectModel {
        let modelURL = NSBundle.mainBundle().URLForResource("iOSSwiftOpenGLCamera", withExtension: "momd")
        _managedObjectModel = NSManagedObjectModel(contentsOfURL: modelURL)
    }
    return _managedObjectModel!
}
var _managedObjectModel: NSManagedObjectModel? = nil

// 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.
var persistentStoreCoordinator: NSPersistentStoreCoordinator {
    if !_persistentStoreCoordinator {
        let storeURL = self.applicationDocumentsDirectory.URLByAppendingPathComponent("iOSSwiftOpenGLCamera.sqlite")
        var error: NSError? = nil
        _persistentStoreCoordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
        if _persistentStoreCoordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: storeURL, options: nil, error: &error) == nil {
            /*
            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.
            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:
            [NSMigratePersistentStoresAutomaticallyOption: true, NSInferMappingModelAutomaticallyOption: true}
            Lightweight migration will only work for a limited set of schema changes; consult "Core Data Model Versioning and Data Migration Programming Guide" for details.
            */
            //println("Unresolved error \(error), \(error.userInfo)")
            abort()
        }
    }
    return _persistentStoreCoordinator!
}
var _persistentStoreCoordinator: NSPersistentStoreCoordinator? = nil

// #pragma mark - Application's Documents directory

// Returns the URL to the application's Documents directory.
var applicationDocumentsDirectory: NSURL {
    let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
    return urls[urls.endIndex-1] as NSURL
}

W Objective C upewnij się, że dodałeś te obiekty do AppDelegate.h

 @property (nonatomic, retain, readonly) NSManagedObjectModel *managedObjectModel;
 @property (nonatomic, retain, readonly) NSManagedObjectContext *managedObjectContext;
 @property (nonatomic, retain, readonly) NSPersistentStoreCoordinator *persistentStoreCoordinator;

 - (NSURL *)applicationDocumentsDirectory; // nice to have to reference files for core data

Zsyntetyzuj poprzednie obiekty w AppDelegate.m jak to:

@synthesize managedObjectContext = _managedObjectContext;
@synthesize managedObjectModel = _managedObjectModel;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;

Następnie dodaj te metody do AppDelegate.m (upewnij się, że w pokazanych miejscach wpisałeś nazwę modelu, który dodałeś):

- (void)saveContext{
    NSError *error = nil;
    NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
    if (managedObjectContext != nil) {
        if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
            abort();
        }
    }
}

- (NSManagedObjectContext *)managedObjectContext{
    if (_managedObjectContext != nil) {
        return _managedObjectContext;
    }

    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (coordinator != nil) {
        _managedObjectContext = [[NSManagedObjectContext alloc] init];
        [_managedObjectContext setPersistentStoreCoordinator:coordinator];
    }
    return _managedObjectContext;
}

- (NSManagedObjectModel *)managedObjectModel{
    if (_managedObjectModel != nil) {
        return _managedObjectModel;
    }
    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"NAMEOFYOURMODELHERE" withExtension:@"momd"];
    _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    return _managedObjectModel;
}

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
    if (_persistentStoreCoordinator != nil) {
        return _persistentStoreCoordinator;
    }

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

    NSError *error = nil;
    _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {

        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }

    return _persistentStoreCoordinator;
}

 #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];
}

Krok 4: Pobierz Obiekty danych do kontrolerów Viewcontrollerów tam, gdzie są potrzebne dane

Wariant 1. Użyj ManagedObjectContext delegata aplikacji z VC (preferowany i łatwiejszy)

Jak zasugerował @brass-kazoo-Odzyskaj odniesienie do AppDelegate i jego managedObjectContext via:

Swift

 let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
 appDelegate.managedObjectContext

Objective C

 [[[UIApplication sharedApplication] delegate] managedObjectContext];

In your ViewController

Opcja 2. Utwórz ManagedObjectContext w swoim VC i dopasuj go do AppDelegate z AppDelegate (Original)

wyświetlanie tylko starej wersji dla Objective C, ponieważ znacznie łatwiej jest użyć preferowanej metody

W kontrolerze ViewController.h

@property (nonatomic, retain) NSManagedObjectContext *managedObjectContext;

W kontrolerze ViewController.m

@synthesize managedObjectContext = _managedObjectContext;

W aplikacji, lub klasa, w której tworzony jest kontroler ViewController, ustawia managedObjectContext na taki sam jak AppDelegate one

ViewController.managedObjectContext = self.managedObjectContext;

Jeśli chcesz, aby ViewController korzystający z Core Data był kontrolerem FetchedResultsController, musisz się upewnić, że te rzeczy znajdują się w Twoim Viewcontrolle.h

@interface ViewController : UIViewController <NSFetchedResultsControllerDelegate> {
  NSFetchedResultsController *fetchedResultsController;
  NSManagedObjectContext *managedObjectContext;
}

 @property (nonatomic, retain) NSFetchedResultsController *fetchedResultsController;

I to jest w ViewController.m

@synthesize fetchedResultsController, managedObjectContext;

Po tym wszystkim możesz teraz użyć managedObjectContext, aby uruchomić wszystkie zwykłe zapytania fetchrequesty potrzebne do dobroci CoreData! Enjoy

 124
Author: ColossalChris,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-12-21 17:55:51

Spróbuj utworzyć core Data backed Cocoa application i spójrz na AppDelegate. Zobaczysz tam metody implementacji baz danych, a także plik managed object model do definiowania jednostek i innych rzeczy przekazywanych z baz danych.

Pokazałeś nam tylko nagłówek (tj. deklarację), ale nie implementację (tj. definicję) podstawowego stosu danych.

 11
Author: Eimantas,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-01-09 08:48:54

Dla Swift 3: zawiera zapisywanie i pobieranie danych

Krok 1 : Dodaj Framework

Tutaj wpisz opis obrazka

Tutaj wpisz opis obrazka

Krok 2: Dodaj model danych

File > New > File > Core Data > Data Model

  • Nazwij plik jako SampleData wynikowy plik będzie SampleData.xcdatamocelId

Krok 3: Dodaj poniższe funkcje do delegata aplikacji i dodaj "Importuj CoreData" do góry

func applicationWillTerminate(_ application: UIApplication) {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    // Saves changes in the application's managed object context before the application terminates.
    self.saveContext()
}


// MARK: - Core Data stack

lazy var persistentContainer: NSPersistentContainer = {
    /*
     The persistent container for the application. This implementation
     creates and returns a container, having loaded the store for the
     application to it. This property is optional since there are legitimate
     error conditions that could cause the creation of the store to fail.
     */


    // SEE BELOW LINE OF CODE WHERE THE 'name' IS SET AS THE FILE NAME (SampleData) FOR THE CONTAINER

    let container = NSPersistentContainer(name: "SampleData")
    container.loadPersistentStores(completionHandler: { (storeDescription, error) in
        if let error = error as NSError? {
            // Replace this implementation with code to handle the error appropriately.
            // fatalError() 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.

            /*
             Typical reasons for an error here include:
             * The parent directory does not exist, cannot be created, or disallows writing.
             * The persistent store is not accessible, due to permissions or data protection when the device is locked.
             * The device is out of space.
             * The store could not be migrated to the current model version.
             Check the error message to determine what the actual problem was.
             */
            fatalError("Unresolved error \(error), \(error.userInfo)")
        }
    })
    return container
}()

// MARK: - Core Data Saving support

func saveContext () {
    let context = persistentContainer.viewContext
    if context.hasChanges {
        do {
            try context.save()
        } catch {
            // Replace this implementation with code to handle the error appropriately.
            // fatalError() 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.
            let nserror = error as NSError
            fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
        }
    }
}

Krok 4: Dodawanie encji i atrybutu do modelu

A) Dodaj Podmiot Tutaj wpisz opis obrazka

B) Dodaj Atrybut Tutaj wpisz opis obrazka

Krok 5: zapisywanie danych

func saveItem(itemToSave: String){
    let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext

//**Note:** Here we are providing the entityName **`Entity`** that we have added in the model
    let entity = NSEntityDescription.entity(forEntityName: "Entity", in: context)
    let myItem = NSManagedObject(entity: entity!, insertInto: context)

    myItem.setValue(itemToSave, forKey: "item")
    do {
        try context.save()
    }
    catch{
        print("There was an error in saving data")
    }
}

Krok 5: pobieranie danych

override func viewWillAppear(_ animated: Bool) {
    // Obtaining data from model
    let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
    let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Entity")

    do {
        let results = try context.fetch(fetchRequest)
        let obtainedResults = results as! [NSManagedObject]
        let firstResult = obtainedResults[0]
        let myValue = firstResult.value(forKey: "item")

        print("myValue: \(myValue)")
    } catch {
        print("Error")
    }
}
 11
Author: kurrodu,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-10-11 07:07:33

Jeśli napotkasz ten sam problem w xcode 4, tak jak ja. Jest inaczej: musiałem wybrać projekt, następnie w targets expand "Link Binary With Libraries" który pokazuje aktualne biblioteki. Stamtąd kliknij znak + (plus), aby wybrać dodatkowe biblioteki, których potrzebujesz. Umieściłem go w górnej części projektu i musiałem go przenieść (przeciągnąć i upuścić) do grupy frameworków , ale to wszystko.

 8
Author: Jay Greene,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-05-01 05:13:20

Jak stwierdził Eimantas, brakuje implementacji stosu rdzenia, jak

- (NSManagedObjectContext *) managedObjectContext;
- (NSManagedObjectModel *)managedObjectMode;
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator;

Rozwiązaniem byłoby utworzenie nowego projektu sterownika danych core i skopiowanie / wklejenie implementacji do projektu.

 5
Author: Henrik P. Hessel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-01-09 08:53:33

Dla Swift 3:

File - > new file - > CoreData - > Model aby utworzyć model.

Zobacz ten link aby uzyskać więcej informacji o tym, jak go wdrożyć.

 4
Author: Taichi Kato,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-11-25 01:02:50

/ / W Swift 2.2 możesz wykonać następujące czynności bez zmiany pliku AppDelegate.

  1. Project - > targets-- > linked framework and libraries Teraz Dodaj nowy framework (kliknij na +) 'CoreData'
  2. File - > new file - > CoreData - > DataModel nazwij to jak mówią A. xcdatamodelid
  3. in A. xcdatamodelid create new enitity (click on entity+) nazwij go say Bc i ustaw jego klasę jako 'Bc' w oknie inspektora po prawej stronie.
  4. Teraz dodaj atrybuty do encji (kliknij atrybuty +), dodaj jeden atrybut dla NP: name i jego typ jako String.
  5. teraz edytor - > Utwórz podklasę NSManagedObject -- > kliknij Dalej w wyskakującym oknie-->ponownie dalej-- > następnie kliknij Utwórz. Zostaną utworzone dwa nowe pliki 1. nowa klasa o nazwie Bc.swift oraz rozszerzenie o nazwie BC+coredataproperties.swift.
  6. File - > new file->iOS - >cocoa Touch class-- > set its subclass as NSObject - > name it as DataController.swift Wewnątrz pliku include ///

    Import UIKit import CoreData class DataController: NSObject {

    var managedObjectContext: NSManagedObjectContext
    
    override  init() {
        // This resource is the same name as your xcdatamodeld contained in your project.
        guard let modelURL = NSBundle.mainBundle().URLForResource("A", withExtension:"momd") else {
            fatalError("Error loading model from bundle")
        }
        // The managed object model for the application. It is a fatal error for the application not to be able to find and load its model.
        guard let mom = NSManagedObjectModel(contentsOfURL: modelURL) else {
            fatalError("Error initializing mom from: \(modelURL)")
        }
        let psc = NSPersistentStoreCoordinator(managedObjectModel: mom)
        self.managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
        self.managedObjectContext.persistentStoreCoordinator = psc
    
        let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
        let docURL = urls[urls.endIndex-1]
        /* The directory the application uses to store the Core Data store file.
        This code uses a file named "A.sqlite" in the application's documents directory.
        */
        let storeURL = docURL.URLByAppendingPathComponent("A.sqlite")
        do {
            try psc.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: storeURL, options: nil)
        } catch {
            fatalError("Error migrating store: \(error)")
        }
    
    }
    

    }

//////

  1. Teraz wewnątrz pliku viewcontroller możesz uzyskać dostęp do swojego db przy użyciu dwóch metod. Ważne : Dołącz instrukcję do kontrolera viewController "import CoreData" a. wywołanie seed () -- >aby wstawić wartość do db / encji b. wywołanie fetch ()--> aby pobrać wartość z db/entity

///////seed ()-->def

func seedPerson() {

        // create an instance of our managedObjectContext
        let moc = DataController().managedObjectContext

        // we set up our entity by selecting the entity and context that we're targeting
        let entity = NSEntityDescription.insertNewObjectForEntityForName("Bc", inManagedObjectContext: moc) as! Bc

        // add our data
        entity.setValue("Meera", forKey: "name")


        // we save our entity
        do {
            try moc.save()
        } catch {
            fatalError("Failure to save context: \(error)")
        }
    }

/ / fetch () def

func fetch() {
        let moc = DataController().managedObjectContext
        let personFetch = NSFetchRequest(entityName: "Bc")

        do {
            let fetchedPerson = try moc.executeFetchRequest(personFetch) as! [Bc]
            print(fetchedPerson.first!.name!)

        } catch {
            fatalError("Failed to fetch person: \(error)")
        }
    }
 1
Author: Meera Raveendran,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-10-02 15:49:46

Widok.h

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

    @interface ViewController :  
    UIViewController<UITableViewDataSource,UITableViewDelegate>

   @property (weak, nonatomic) IBOutlet UITableView *coreDataList;
   - (IBAction)addBtnClick:(id)sender;
   @property (strong, nonatomic) NSMutableArray *dataList;
   @end
Szczegóły.h
  #import <UIKit/UIKit.h>
  #import <CoreData/CoreData.h>

 @interface DetailViewController : UIViewController<UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UITextField *nameTxt;
@property (weak, nonatomic) IBOutlet UITextField *mobileTxt;
@property (weak, nonatomic) IBOutlet UITextField *emailIdTxt;
 - (IBAction)saveBtnClick:(id)sender;
@property (strong,nonatomic) NSManagedObject *userData;

@end
 0
Author: sasidharan.M,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-02-11 02:20:16
  - (void)viewDidLoad {
  [super viewDidLoad];
  // Do any additional setup after loading the view.
   if (self.userData) {
    [self.nameTxt setText:[self.userData valueForKey:@"name"]];
    [self.mobileTxt setText:[self.userData 
     valueForKey:@"mobileNumber"]];
    [self.emailIdTxt setText:[self.userData valueForKey:@"email"]];
    [self.imgView setImage:[UIImage imageWithData:[self.userData 
     valueForKey:@"imageView"]]];    }
        }

  - (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
  }


  - (BOOL)textFieldShouldReturn:(UITextField *)textField
  {
   [textField resignFirstResponder];
return YES;
 }
  /*
  #pragma mark - Navigation



 - (IBAction)browseBtn:(id)sender
   {

  UIImagePickerController *imgpic =[[UIImagePickerController      
     alloc]init];     
  imgpic .delegate =self;
 imgpic .sourceType =UIImagePickerControllerSourceTypePhotoLibrary;
[self presentViewController:imgpic animated:YES completion:nil];

 }
 -(void)imagePickerController:(UIImagePickerController *)picker 
 didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
 {
  UIImage *choose = info[UIImagePickerControllerOriginalImage];
self.imgView.image=choose;
[picker dismissViewControllerAnimated:YES completion:nil];
}


  - (IBAction)saveBtnClick:(id)sender {

 NSManagedObjectContext *context = [self managedObjectContext];

 if (self.userData) {
    // Update existing data
    [self.userData setValue:self.nameTxt.text forKey:@"name"];
    [self.userData setValue:self.mobileTxt.text 
     forKey:@"mobileNumber"];        
   [self.userData setValue:self.emailIdTxt.text forKey:@"email"];

    UIImage *sampleimage = _imgView.image;
    NSData *dataImage = UIImageJPEGRepresentation(sampleimage, 1.0);
            [self.userData setValue:dataImage forKey:@"imageView"];

    } else {
    // Create a new data
    NSManagedObject *newDevice = [NSEntityDescription 
     insertNewObjectForEntityForName:@"Details" 
     inManagedObjectContext:context];
    [newDevice setValue:self.nameTxt.text forKey:@"name"];
    [newDevice setValue:self.mobileTxt.text forKey:@"mobileNumber"];
    [newDevice setValue:self.emailIdTxt.text forKey:@"email"];
    UIImage *sampleimage = _imgView.image;
    NSData *dataImage = UIImageJPEGRepresentation(sampleimage, 1.0);

    [newDevice setValue:dataImage forKey:@"imageView"];

  }

  NSError *error = nil;
 // Save the object to persistent store
 if (![context save:&error]) {
    NSLog(@"Can't Save! %@ %@", error, [error localizedDescription]);
 }

 [self dismissViewControllerAnimated:YES completion:nil];
 }
   @end

.h

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

 @interface DetailViewController :
 UIViewController<UITextFieldDelegate,UINavigationControllerDelegate,            
     UIIma
    gePickerControllerDelegate>
         @property (weak, nonatomic) IBOutlet UITextField *nameTxt;
  @property (weak, nonatomic) IBOutlet UITextField *mobileTxt;
 @property (weak, nonatomic) IBOutlet UITextField *emailIdTxt;
  @property (weak, nonatomic) IBOutlet UIImageView *imgView;
 - (IBAction)browseBtn:(id)sender;
 - (IBAction)saveBtnClick:(id)sender;
@property (strong,nonatomic) NSManagedObject *userData;

@end
 0
Author: sasidharan.M,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-25 03:15:23
 let alert  = UIAlertController(title:"Error", message: "No Internet Connection", preferredStyle: .alert)
            alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: { (action) in}))
            alert.addAction(UIAlertAction(title: "Try Again", style: .default, handler: { (action) in
                self.networkCall(text: self.daySelected)
            }))
            self.present(alert, animated: false, completion: nil)
 0
Author: Amannnn,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-06-15 10:33:01
+(void) insetPlusUpdate:(NSDictionary *)dataa {

    NSManagedObjectContext * context;

    if (![[NSThread currentThread] isMainThread]) {

        context = [[NSManagedObjectContext alloc] init];

        [context setPersistentStoreCoordinator:[APP_DELEGATE persistentStoreCoordinator]];
    } else {

        context = [APP_DELEGATE managedObjectContext];
    }

    NSFetchRequest * request = [[NSFetchRequest alloc] init];

    NSEntityDescription * entity = [NSEntityDescription entityForName:@"EntityName" inManagedObjectContext:context];

    [request setEntity:entity];

    NSPredicate * check = [NSPredicate predicateWithFormat:@"attribute == %@", Dict[@"key"]];

    [request setPredicate:check];

    NSError * error = nil;

    if ([context countForFetchRequest:request error:&error] == 0) {

Entity.attribute = @"";

    } else {


        NSArray * array = [context executeFetchRequest:request error:&error];

        EntityName * entity = [array firstObject];

  Entity.attribute = @"";

    }

}

+(NSString *)fetch:(NSString *)feed_id{

    NSManagedObjectContext * context;

    if(![[NSThread currentThread] isMainThread]){

        context = [[NSManagedObjectContext alloc] init];

        [context setPersistentStoreCoordinator:[APP_DELEGATE persistentStoreCoordinator]];

    } else {

        context = [APP_DELEGATE managedObjectContext];

    }

    NSFetchRequest * request = [[NSFetchRequest alloc] init];

    NSEntityDescription * entity = [NSEntityDescription entityForName:@"ENTITYNAME" inManagedObjectContext:context];

    [request setEntity:entity];

   NSPredicate * check = [NSPredicate predicateWithFormat:@"attribute == %@", Dict[@"key"]];

    [request setPredicate:check];

    NSError * error = nil;

    if ([context countForFetchRequest:request error:&error] > 0) {

        NSArray * array = [context executeFetchRequest:request error:&error];

        ENTITYNAME * fetchData = [array firstObject];

        NSString * string = fetchData.attribte[@"key"];

        return string;
    }

    return nil;
}


+(BOOL)delete{

    NSManagedObjectContext * context;

    if (![[NSThread currentThread] isMainThread]) {

        context = [[NSManagedObjectContext alloc] init];

        [context setPersistentStoreCoordinator:[APP_DELEGATE persistentStoreCoordinator]];

    } else {

        context = [APP_DELEGATE managedObjectContext];

    }

    NSFetchRequest * request = [[NSFetchRequest alloc] init];

    NSEntityDescription * entity = [NSEntityDescription entityForName:@"ENTITYNAME" inManagedObjectContext:context];

    [request setEntity:entity];

    NSError *error = nil;

    NSBatchDeleteRequest *deleteRequest = [[NSBatchDeleteRequest alloc] initWithFetchRequest: request];

    @try{

        [context executeRequest:deleteRequest error:&error];
        if([context save:&error]){

            NSLog(@"Deleted");

            return [context save:&error];

        }
        else{

            return [context save:&error];
        }

    }
    @catch(NSException *exception){

        NSLog(@"failed %@",exception);
        return [context save:&error];
    }    


}
 0
Author: Slimshady,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-06-22 07:21:45

Przykładowy widok kodowania 1

#import "ViewController.h"
#import "DetailViewController.h"

 @interface ViewController ()
 {
  NSInteger indexPathvalue;
 }
 @end

  @implementation ViewController

 - (NSManagedObjectContext *)managedObjectContext {
     NSManagedObjectContext *context = nil;
     id delegate = [[UIApplication sharedApplication] delegate];
     if ([delegate performSelector:@selector(managedObjectContext)]) {
       context = [delegate managedObjectContext];
     }
   return context;
  }

  - (void)viewDidLoad {
      [super viewDidLoad];
  // Do any additional setup after loading the view, typically from a nib.
    NSLog(@"call this one2");
 }

 - (void)viewDidAppear:(BOOL)animated
 {
   [super viewDidAppear:animated];
   NSManagedObjectContext *managedObjectContext = [self 
   managedObjectContext];
   NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] 
   initWithEntityName:@"Details"];
   self.dataList = [[managedObjectContext executeFetchRequest:fetchRequest   
   error:nil] mutableCopy];
   [_coreDataList reloadData];

    NSLog(@"call this one");
 }
    #pragma mark - Table view data source

   - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
   {
     return 1;
   }

     - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:
   (NSInteger)section
    {
    return self.dataList.count;
    }

   - (UITableViewCell *)tableView:(UITableView *)tableView 
   cellForRowAtIndexPath:(NSIndexPath *)indexPath
   {
   static NSString *CellIdentifier = @"Cell";
   UITableViewCell *cell = [tableView     
   dequeueReusableCellWithIdentifier:CellIdentifier];

     if (cell == nil)
    {
    cell = [[UITableViewCell   
    alloc]initWithStyle:UITableViewCellStyleSubtitle 
    reuseIdentifier:CellIdentifier];
    }

   NSManagedObject *user = [self.dataList objectAtIndex:indexPath.row];
   cell.textLabel.text = [user valueForKey:@"name"];
      cell.detailTextLabel.text = [user valueForKey:@"mobileNumber"];
    cell.imageView.image = [UIImage imageWithData:[user
    valueForKey:@"imageView"]]; 
    return cell;
    }


    - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:
    (NSIndexPath *)indexPath
    {
    indexPathvalue = indexPath.row;
    [self performSegueWithIdentifier:@"detailView" sender:self];
    }

     - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:
    (NSIndexPath *)indexPath
    {
     return YES;
     }
     - (void)tableView:(UITableView *)tableView commitEditingStyle:
      (UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:
     (NSIndexPath *)indexPath
    {
    NSManagedObjectContext *context = [self managedObjectContext];
    if (editingStyle == UITableViewCellEditingStyleDelete)
    {
    [context deleteObject:[self.dataList objectAtIndex:indexPath.row]];
    NSError *error = nil;
    if (![context save:&error]) {
        NSLog(@"Can't Delete! %@ %@", error, [error localizedDescription]);
        return;
    }
    [self.dataList removeObjectAtIndex:indexPath.row];
    [_coreDataList reloadData];

     }

    }
   - (void)didReceiveMemoryWarning {
   [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    }

   - (IBAction)addBtnClick:(id)sender {
    }


    #pragma mark - Navigation

    // In a storyboard-based application, you will often want to do a little      
    - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
     {
   // Get the new view controller using [segue destinationViewController].
   // Pass the selected object to the new view controller.
    if ([segue.identifier isEqualToString:@"detailView"])
   {
    NSManagedObject *obj = [self.dataList objectAtIndex:indexPathvalue];
    DetailViewController *detail = segue.destinationViewController;
    detail.userData = obj;
    }

    }
   @end

Przykładowy widok szczegółów

       #import "DetailViewController.h"

       @interface DetailViewController ()

       @end

       @implementation DetailViewController

      - (NSManagedObjectContext *)managedObjectContext {
     NSManagedObjectContext *context = nil;
     id delegate = [[UIApplication sharedApplication] delegate];
     if ([delegate performSelector:@selector(managedObjectContext)]) {
    context = [delegate managedObjectContext];
     }
     return context;
    }

    - (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
     if (self.userData) {
    [self.nameTxt setText:[self.userData valueForKey:@"name"]];
    [self.mobileTxt setText:[self.userData valueForKey:@"mobileNumber"]];
    [self.emailIdTxt setText:[self.userData valueForKey:@"email"]];
    }
    }

     - (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    }


   - (BOOL)textFieldShouldReturn:(UITextField *)textField
   {
    [textField resignFirstResponder];
    return YES;




}
     /*

Savebutton

    - (IBAction)saveBtnClick:(id)sender {

     NSManagedObjectContext *context = [self managedObjectContext];

     if (self.userData) {
    // Update existing data
    [self.userData setValue:self.nameTxt.text forKey:@"name"];
    [self.userData setValue:self.mobileTxt.text forKey:@"mobileNumber"];
    [self.userData setValue:self.emailIdTxt.text forKey:@"email"];
    UIImage *sampleimage = [UIImage imageNamed:@"icon.png"];
    NSData *dataImage = UIImageJPEGRepresentation(sampleimage, 1.0);
    [self.userData setValue:dataImage forKey:@"imageView"];

     } else {
    // Create a new data
    NSManagedObject *newDevice = [NSEntityDescription   
    insertNewObjectForEntityForName:@"Details" 
    inManagedObjectContext:context];
    [newDevice setValue:self.nameTxt.text forKey:@"name"];
    [newDevice setValue:self.mobileTxt.text forKey:@"mobileNumber"];
    [newDevice setValue:self.emailIdTxt.text forKey:@"email"];
    UIImage *sampleimage = [UIImage imageNamed:@"icon.png"];
    NSData *dataImage = UIImageJPEGRepresentation(sampleimage, 1.0);
    [newDevice setValue:dataImage forKey:@"imageView"];

     }

     NSError *error = nil;
    // Save the object to persistent store
     if (![context save:&error]) {
    NSLog(@"Can't Save! %@ %@", error, [error localizedDescription]);
    }

    [self dismissViewControllerAnimated:YES completion:nil];
    }
   @end
 0
Author: sasidharan.M,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-06-22 08:39:57