Добавление основных данных в существующий проект iPhone
Я хотел бы добавить основные данные в существующий проект iPhone, но я все еще получаю много ошибок компиляции:
- NSManagedObjectContext undeclared
- Expected specifier-qualifier-list before 'NSManagedObjectModel'
- ...
Я уже добавил основную базу данных к цели (щелкните правой кнопкой мыши мой проект в разделе "Цели", "Добавить" - "Существующие рамки", "CoreData.framework" ).
Мой заголовочный файл:
NSManagedObjectModel *managedObjectModel;
NSManagedObjectContext *managedObjectContext;
NSPersistentStoreCoordinator *persistentStoreCoordinator;
[...]
@property (nonatomic, retain, readonly) NSManagedObjectModel *managedObjectModel;
@property (nonatomic, retain, readonly) NSManagedObjectContext *managedObjectContext;
@property (nonatomic, retain, readonly) NSPersistentStoreCoordinator *persistentStoreCoordinator;
Что мне не хватает? Запуск нового проекта не является вариантом...
Спасибо большое!
изменить
извините, у меня есть эти реализации... но похоже, что библиотека отсутствует... методы реализации полны с ошибкой компиляции типа "managedObjectContext undeclared
", "NSPersistentStoreCoordinator undeclared
", но также с "Ожидаемым" ) до NSManagedObjectContext
"(хотя кажется, что скобки правильны)...
#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 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;
}
Ответы
Ответ 1
Все заголовочные файлы CoreData импортируются в App_Prefix.pch
, поэтому классы CoreData будут доступны во всем вашем проекте, поэтому вам не нужно вручную импортировать заголовок в нужные вам файлы.
Итак, откройте Xcode и найдите файл типа App_Prefix.pch
, по умолчанию это в группе Other Sources
. После оператора импорта UIKit
добавьте следующую строку:
#import <CoreData/CoreData.h>
И вы должны быть готовы к работе.
Xcode 4
Для проектов, созданных в Xcode 4, файл префикса можно найти в группе Supporting Files
в навигаторе проекта. Он по умолчанию назвал "projectname-Prefix.pch".
Xcode 6 +
Начиная с Xcode 6, предварительно скомпилированный файл заголовка больше не включается по умолчанию. Это связано с введением модулей, которые убирают необходимость использования предварительно скомпилированных заголовков. Хотя по-прежнему можно вручную добавить файл PCH для глобального включения заголовков CoreData, рассмотрите возможность задания зависимости CoreData с помощью @import CoreData;
* в каждом файле, использующем CoreData. Это делает явные и более важные зависимости во избежание этой проблемы в будущем.
* Модули должны быть включены, чтобы это работало.
Ответ 2
Просто изложите все шаги, которые вам действительно нужно выполнить, чтобы добавить Core Data в проект, который ранее не имел его:
Шаг 1: добавьте фреймворк
Нажмите на целевую страницу приложения (на левой панели ее верхний значок с именем вашего приложения), затем перейдите на вкладку "Сборка фаз", затем в "Связывание двоичных файлов с библиотеками", щелкните маленькую цифру "+" на затем найдите "CoreData.framework" и добавьте его в свой проект
Затем либо импортируйте coredata на все объекты, в которых вы нуждаетесь (без сексапильного способа), используя:
Swift
import CoreData
Цель C
#import <CoreData/CoreData.h>
или добавьте импорт под общим импортом в ваш .pch файл (гораздо более сексуальный), например:
#ifdef __OBJC__
#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>
#endif
Шаг 2: добавьте модель данных
Чтобы добавить файл .xcdatamodel, щелкните правой кнопкой мыши/щелкните правой кнопкой мыши на ваших файлах в правой панели (например, в папке "Ресурсы" для безопасного хранения) и выберите "Добавить новый файл". Перейдите на вкладку "Основные данные" при выборе типа файла затем нажмите "Модель данных", дайте ему имя и нажмите "Далее" и "Готово", и он добавит его в ваш проект. Когда вы нажмете на этот объект модели, вы увидите, что интерфейс добавит объекты в ваш проект с любыми отношениями, которые вы хотите.
Шаг 3: Обновить делегат приложения
В Swift на 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 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 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 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 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 Documents directory
// Returns the URL to the application Documents directory.
var applicationDocumentsDirectory: NSURL {
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.endIndex-1] as NSURL
}
В Цель C обязательно добавьте эти объекты в 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
Синтезировать предыдущие объекты в AppDelegate.m следующим образом:
@synthesize managedObjectContext = _managedObjectContext;
@synthesize managedObjectModel = _managedObjectModel;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;
Затем добавьте эти методы в AppDelegate.m(не забудьте указать имя модели, которую вы добавили в показанных точках):
- (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 Documents directory
// Returns the URL to the application Documents directory.
- (NSURL *)applicationDocumentsDirectory{
return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}
Шаг 4: Получить объекты данных в ViewControllers, где вам нужны данные
Вариант 1. Используйте делегат приложения ManagedObjectContext из VC (предпочтительный и упрощенный)
Как предложено @brass-kazoo - Получить ссылку на AppDelegate и его управляемый объект ObjectContext с помощью:
Swift
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
appDelegate.managedObjectContext
Цель C
[[[UIApplication sharedApplication] delegate] managedObjectContext];
в вашем ViewController
Вариант 2. Создайте ManagedObjectContext в своем VC и совместите AppDelegate с AppDelegate (Оригинал)
Показывает только старую версию для Objective C, поскольку гораздо проще использовать предпочтительный метод
в ViewController.h
@property (nonatomic, retain) NSManagedObjectContext *managedObjectContext;
В ViewController.m
@synthesize managedObjectContext = _managedObjectContext;
В AppDelegate или классе, где создан ViewController, установите для managedObjectContext тот же самый, что и AppDelegate
ViewController.managedObjectContext = self.managedObjectContext;
Если вы хотите, чтобы viewcontroller с использованием Core Data был FetchedResultsController, вам нужно убедиться, что этот материал находится в вашем ViewController.h
@interface ViewController : UIViewController <NSFetchedResultsControllerDelegate> {
NSFetchedResultsController *fetchedResultsController;
NSManagedObjectContext *managedObjectContext;
}
@property (nonatomic, retain) NSFetchedResultsController *fetchedResultsController;
И это в ViewController.m
@synthesize fetchedResultsController, managedObjectContext;
После всего этого вы можете теперь использовать этот управляемый объектObjectContext для запуска всех обычных fetchRequests, необходимых для обеспечения CoreData! Наслаждайтесь
Ответ 3
Попробуйте создать приложение с поддержкой Core Data с поддержкой Cocoa и посмотрите AppDelegate. Вы увидите основные методы реализации стека данных, а также файл управляемой модели объекта для определения ваших объектов и других материалов, выпущенных с помощью ядра.
Вы показали нам только заголовок (т.е. объявление), но не реализацию (т.е. определение) в стеке Core Data.
Ответ 4
Если вы столкнулись с этой же проблемой в xcode 4, как и я.
Другое дело: мне нужно было выбрать проект, а затем в целевых расширениях "Связывание двоичных файлов с библиотеками" , в котором отображаются текущие библиотеки.
Оттуда щелкните знак + (плюс), чтобы выбрать любые дополнительные библиотеки, в которых вы нуждаетесь.
Я разместил его в верхней части проекта и должен был переместить его (перетащить) в Frameworks Group, но это было.
Ответ 5
Для Swift 3: ВКЛЮЧАЕТ СОХРАНЕНИЕ И ВОЗВРАТ ДАННЫХ
Шаг 1: добавить структуру
![введите описание изображения здесь]()
![введите описание изображения здесь]()
Шаг 2: Добавить модель данных
Файл > Создать > Файл > Основные данные > Модель данных
- Назовите файл как
SampleData
результирующий файл будет SampleData.xcdatamocelId
Шаг 3: Добавьте перечисленные ниже функции в ваш делегат приложения и добавьте "import CoreData" в начало
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application 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)")
}
}
}
ШАГ 4: Добавление объекта и атрибута к модели
a) Добавить объект
![введите описание изображения здесь]()
b) Добавить атрибут
![введите описание изображения здесь]()
ШАГ 5: Сохранение данных
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")
}
}
ШАГ 5: Получение данных
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")
}
}
Ответ 6
Поскольку Эймантас заявил, что вам не хватает реализации Core Stack, например
- (NSManagedObjectContext *) managedObjectContext;
- (NSManagedObjectModel *)managedObjectMode;
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator;
В решении было бы создать новый проект драйверов основных данных и скопировать/вставить реализацию в ваш проект.
Ответ 7
Для Swift 3:
Файл- > новый файл- > CoreData- > Модель для создания модели.
Обратитесь к этой ссылке для получения дополнительной информации о том, как ее реализовать.
Ответ 8
//в Swift 2.2 вы можете сделать следующее без изменения файла AppDelegate.
- Project- > target → связанные структуры и библиотеки
Теперь добавьте новую фреймворк (нажмите +) "CoreData"
- Файл- > новый файл- > CoreData- > DataModel
назовите его как say A.xcdatamodelid
- В A.xcdatamodelid создайте новую enitity (щелкните по объекту +)
назовите его как say Bc и установите его класс как "Bc" в окне инспектора справа.
- Теперь добавьте атрибуты сущности (щелкните атрибуты +), добавьте один атрибут, например: name и его тип, как String.
- Теперь editor- > создайте подкласс NSManagedObject → щелкните далее по всплывающему окну → снова рядом → , затем нажмите "Создать".
Создаются два новых файла: 1. новый класс с именем Bc.swift и расширение с именем Bc + coredataproperties.swift.
-
File- > new file- > ios → cocoa Touch class → установить свой подкласс как NSObject- > называть его DataController.swift
Внутри файла есть
///
import UIKit
импортировать 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 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)")
}
}
}
//////
- Теперь в файле viewcontroller вы можете получить доступ к своему db, используя два метода.
Важно: включить выражение в свой viewController "import CoreData"
а. call seed() → , чтобы вставить значение в db/entity
б. call fetch() → для извлечения значения из db/entity
///////семена() → Защита
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)")
}
}
Ответ 9
+ (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) {удалить
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];
}
}
Ответ 10
пример кодирования view1
#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
образец подробного представления
#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
Ответ 11
view.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
detail.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
Ответ 12
- (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