- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试使用 Core Data 让用户可以添加最喜欢的汽车。用户可以选择品牌(在单独的 tableviewcontroller 中)、模型(文本字段)和年份(文本字段)。这些汽车将显示在 tableview 上。
我想我正确地实现了 CoreData,但我得到“由于未捕获的异常 'NSInvalidArgumentException' 而终止应用程序,原因:'+entityForName: nil 不是合法的 NSManagedObjectContext”。我不知道是什么导致我的 managedObjectContent 等于 nil。
这是第一个 View 。这将显示一系列最喜欢的汽车。
#import "addCar.h"
#import "dreamCar.h"
@implementation dreamCar
@synthesize dreamCarArray;
// Retrieve managed object context and later save the data
-(NSManagedObjectContext *)managedObjectContext{
NSManagedObjectContext *context = nil;
id delegate = [[UIApplication sharedApplication] delegate];
if([delegate performSelector:@selector(managedObjectContext)]){
context = [delegate managedObjectContext];
}
return context;
}
-(void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
// Get cars from database
NSManagedObjectContext *moc = [self managedObjectContext];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc]initWithEntityName:@"Cars"];
dreamCarArray = [[moc executeFetchRequest:fetchRequest error:nil]mutableCopy];
[self.tableView reloadData];
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return dreamCarArray.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath: (NSIndexPath *)indexPath{
static NSString *cellIdentifier = @"dreamCarCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
// Configure the cell
NSManagedObject *car = [dreamCarArray objectAtIndex:indexPath.row];
[cell.textLabel setText:[NSString stringWithFormat:@"%@ %@ %@", [car valueForKey:@"year"],[car valueForKey:@"make"],[car valueForKey:@"model"]]];
return cell;
}
@end
#import "addCar.h"
#import "addDreamCarMake.h"
@implementation addCar
@synthesize makeText,modelText,yearText,car;
// Retrieve managed object context and later save the data
-(NSManagedObjectContext *)managedObjectContext{
NSManagedObjectContext *context = nil;
id delegate = [[UIApplication sharedApplication] delegate];
if([delegate performSelector:@selector(managedObjectContext)]){
context = [delegate managedObjectContext];
}
return context;
}
-(void)viewDidLoad{
[super viewDidLoad];
self.modelText.delegate = self;
self.yearText.delegate = self;
if(car){
[self.makeText setText:[car valueForKey:@"make"]];
[self.modelText setText:[car valueForKey:@"model"]];
[self.yearText setText:[car valueForKey:@"year"]];
}
}
//If cancel button is pressed, pop current view from stack
- (IBAction)cancelButtonPressed:(id)sender {
[self.navigationController popToRootViewControllerAnimated:YES];
}
// If done button is pressed
- (IBAction)doneButtonPressed:(id)sender {
NSManagedObjectContext *context = [self managedObjectContext];
// Create new Car
NSManagedObject *newCar = [NSEntityDescription insertNewObjectForEntityForName:@"Cars" inManagedObjectContext:context];
[newCar setValue:makeText forKey:@"make"];
[newCar setValue:modelText forKey:@"model"];
[newCar setValue:yearText forKey:@"year"];
//Pop current view from stack
[self.navigationController popToRootViewControllerAnimated:YES];
}
// Unwind segue from addDreamCarMake
- (IBAction)unwindToListFromAddMake:(UIStoryboardSegue *)segue{
addDreamCarMake *segue1 = segue.sourceViewController;
self.makeText.text = segue1.makeName;
}
//Dismiss Keyboard
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
[self.modelText resignFirstResponder];
[self.yearText resignFirstResponder];
}
// Dismiss Keyboard
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
if(textField){
[textField resignFirstResponder];
}
return NO;
}
@end
#import "addCar.h"
#import "addDreamCarMake.h"
static NSString* makeLabel;
@implementation addDreamCarMake
@synthesize makeName;
- (void)viewDidLoad
{
[super viewDidLoad];
//Initial Dictionary
makes = @{ @"A" : @[@"Acura",
@"AJS",
@"Alfa Romeo",
@"Allard",
@"Allis Chalmers",
@"AM General",
@"AMC",
@"American",
@"American Motors",
@"Amphicar",
@"Ancarrow",
@"Ariel",
@"Arnolt",
@"Arnolt Bristol",
@"Art Work",
@"Assembled",
@"Aston Martin",
@"ASVE",
@"ASVE",
@"Auburn",
@"Audi",
@"Aurora",
@"Austin",
@"Austin-Healey",
@"Avanti",],
@"B" : @[@"Bay Marine",
@"Beck",
@"Bentley",
@"BMW",
@"Borum",
@"Boss",
@"Bourget",
@"Brainerd Robbins",
@"Bricklin",
@"BSA",
@"Bugatti",
@"Buick",],
@"C" : @[@"C Boat",
@"Cadillac",
@"Callaway",
@"Caterpillar",
@"CAV",
@"Century",
@"Checker",
@"Chevrolet",
@"Chris-Craft",
@"Chris-Craft/Dewhurst",
@"Chrysler",
@"Cobra",
@"Concept",
@"Condor",
@"Cord",
@"Crosley",
@"Cushman",
@"Custom",
@"Custom Built",
@"CZ",],
@"D" : @[@"Daewoo",
@"Daihatsu",
@"Daimler",
@"Dan Kidney",
@"Datsun",
@"Delorean",
@"DeSoto",
@"DeTomaso",
@"Diamond",
@"Dingle",
@"DKW",
@"Dodge",
@"Dodge ",
@"Dry Lakes",
@"Duck Boat",
@"Duesenberg",
@"Dunphy",
@"Dyno",],
@"E" : @[@"Eagle",
@"Eddie Trotta",
@"Edmunds-Kenyon",
@"Edsel",
@"Era",
@"Essex",
@"Evinrude",
@"Excalibur",
@"Eysink",],
@"F" : @[@"Factory Five",
@"Fantasy",
@"Farmall",
@"Ferrari",
@"Fiat",
@"Fleetwood",
@"Ford",
@"Forsa",
@"Framed Art",
@"Franklin",
@"Frazer",],
@"G" : @[@"Gar Wood",
@"Gar Wood/Michaud",
@"Gasoline Pump",
@"Geo",
@"Glen-L",
@"GM",
@"GMC",
@"Goodhue & Hawkins",
@"Graham",
@"Greavette",
@"Griffith",],
@"H" : @[@"Hacker",
@"Hackercraft",
@"Harley-Davidson",
@"Hendrick Motorsports",
@"Henry J",
@"Hickman",
@"Higgins ",
@"Hillman",
@"Hogzoom",
@"Holden",
@"Honda",
@"Horex",
@"Hudson",
@"Hummer",
@"Hunter",
@"Hupmobile",
@"Hutchinson",
@"Hyundai",],
@"I" : @[@"IH",
@"IH Farmall",
@"Imperial",
@"Indian",
@"Indian Lakes",
@"Infiniti",
@"International",
@"Isotta",
@"Isuzu",],
@"J" : @[@"Jaguar",
@"JBL",
@"Jeep",
@"Jensen",
@"John Deere",
@"Johnson",],
@"K" : @[@"Kaiser",
@"Kia",
@"KR Proton",
@"Kurtis",],
@"L" : @[@"Lagonda",
@"Lamborghini",
@"Land Rover",
@"Larson",
@"Lasalle",
@"Lexus",
@"Lighted Sign",
@"Lincoln",
@"Lola",
@"Lotus",
@"Lucky Fire",
@"Luyere",
@"Lyman",],
@"M" : @[@"MAC Tools",
@"Mack",
@"Malibu",
@"Maserati",
@"Massey-Harris",
@"Matchless",
@"Maxton",
@"Mazda",
@"McCormick",
@"McLaren",
@"Memorabilia",
@"Mercedes-Benz",
@"Mercury",
@"Merkur",
@"Metal Sign",
@"MG",
@"Midget",
@"Mini",
@"Mitsubishi",
@"Model",
@"Moore",
@"Morris",
@"Mugen",
@"Murray",
@"MV Agusta",],
@"N" : @[@"N.U.T.",
@"Nash",
@"Neon Sign",
@"Nissan",
@"Norton",
@"NSU",],
@"O" : @[@"Oakland",
@"OCC",
@"Oldsmobile",
@"Oliver Hart-Parr",],
@"P" : @[@"Pabst ",
@"Pace Arrow",
@"Packard",
@"Panoz",
@"Panther",
@"Parts",
@"Penn Yan",
@"Peugeot",
@"Pierce-Arrow",
@"Plastic Sign",
@"Plymouth",
@"Pontiac",
@"Porcelain Sign",
@"Porsche",
@"Prevost",
@"Pulse",],
@"Q" : @[@"Qvale",],
@"R" : @[@"Racing ",
@"Rambler",
@"Reading-Standard",
@"Renault",
@"Reo",
@"Replica",
@"Replicar",
@"Retrovette",
@"Revcon",
@"Richardson",
@"Riva",
@"Rolls-Royce",],
@"S" : @[@"Saab",
@"Saleen",
@"Saturn",
@"Schwinn",
@"Scorpion",
@"Sea Lyon",
@"Seagrave",
@"Shay",
@"Shelby",
@"Shepherd",
@"SIMCA",
@"Sims",
@"Skiff Craft",
@"Speed Sport",
@"Star",
@"Staudacher",
@"Sterling",
@"Steve McQueen",
@"Steyr-Daimler Puch",
@"Stone Boatyard",
@"Studebaker",
@"Subaru",
@"Sudlow",
@"Sunbeam",
@"Sunflower",
@"Superformance",
@"Suzuki",],
@"T" : @[@"Thompson",
@"Tidal Force",
@"Tiffany",
@"Tin Sign",
@"Toyota",
@"Trigre",
@"Triumph",
@"Truscott",
@"TVR",],
@"V" : @[@"Ventnor",
@"Vincent",
@"Volkswagen",
@"Volvo",],
@"W" : @[@"Wagner",
@"Westcott",
@"Whiticar",
@"Whizzer",
@"Willys",
@"Wise & Sons",
@"Wise Boat & Bus Works",],
@"Y" : @[@"Yamaha",
@"Yamaha Castrol",
@"Yellow Jacket",],
@"Z" : @[@"Zimmer",
@"Zundapp",]},
makeSectionTitles = [[makes allKeys] sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return [makeSectionTitles count];
}
// Title at each section
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
return [makeSectionTitles objectAtIndex:section];
}
// Number of rows
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
NSString *sectionTitle = [makeSectionTitles objectAtIndex:section];
NSArray *sectionModels = [makes objectForKey:sectionTitle];
return [sectionModels count];
}
// Item at each cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"addDreamCarMakeCell" forIndexPath:indexPath];
// Configure the cell...
NSString *sectionTitle = [makeSectionTitles objectAtIndex:indexPath.section];
NSArray *sectionmodels = [makes objectForKey:sectionTitle];
NSString *model = [sectionmodels objectAtIndex:indexPath.row];
cell.textLabel.text = model;
return cell;
}
// Index on the left side
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
return makeSectionTitles;
}
// If back button is pressed, pop current view from stack
- (IBAction)backButtonPressed:(id)sender {
[self.navigationController popToRootViewControllerAnimated:YES];
}
// Segue
-(void) prepareForSegue: (UIStoryboardSegue *)segue sender: (UITableViewCell *)sender {
//Segue back to searchCar
if ([segue.identifier isEqualToString:@"addMakeCompleted"]) {
makeLabel = sender.textLabel.text;
self.makeName = makeLabel;
}
}
@end
#import <UIKit/UIKit.h>
@interface infoMobileAppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@property (weak, nonatomic) NSManagedObjectContext *managedObjectContext;
@property (weak, nonatomic) NSManagedObjectContext *managedObjectModel;
@property (weak, nonatomic) NSManagedObjectContext *persistentStoreCoordinator;
@end
#import "infoMobileAppDelegate.h"
@implementation infoMobileAppDelegate
@synthesize managedObjectContext = _managedObjectContext;
@synthesize managedObjectModel = _managedObjectModel;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
return YES;
}
@end
-(void)viewDidLoad{
[super viewDidLoad];
self.modelText.delegate = self;
self.yearText.delegate = self;
if(car){
[self.makeText setText:[car valueForKey:@"make"]];
[self.modelText setText:[car valueForKey:@"model"]];
[self.yearText setText:[car valueForKey:@"year"]];
}
}
- (void)saveContext
{
NSError *error = nil;
NSManagedObjectContext *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.
NSLog(@"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.
- (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 from the application's model.
- (NSManagedObjectModel *)managedObjectModel
{
if (_managedObjectModel != nil) {
return _managedObjectModel;
}
NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"coreDataInfoNet" 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 (_persistentStoreCoordinator != nil) {
return _persistentStoreCoordinator;
}
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"coreDataInfoNet.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.
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:@YES, NSInferMappingModelAutomaticallyOption:@YES}
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]);
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];
}
@end
最佳答案
丢弃 if
怎么样? View Controller 中的语句?
如果您使用“空应用程序”模板启动一个新的 Xcode 项目并单击“使用核心数据”复选框,您将在应用程序委托(delegate)中看到所需的代码
// note that you need to import the header to see the properties directly
#import "AppDelegate.h"
AppDelegate *myApp = [UIApplication sharedApplication];
NSManagedObjectContext *moc = myApp.managedObjectContext;
// use the moc as required....
nil
然后取决于
if
语句将其设置为非零值。
关于ios - entityForName :nil Issue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23178433/
在检查对象是否为 nil 时,有人使用 1: if (object == nil) { //... } 有人用 2: if (nil == object) { //... } 1和2有
func InsertApData(w http.ResponseWriter, r *http.Request) { decoder := json.NewDecoder(r.Body)
为什么 nil.to_s 返回 "",而 nil.inspect 返回 "nil"(当显然 .inspect 使用 .to_s 方法) 最佳答案 "inspect" method of the Obj
运行时间 https://play.golang.org/p/sl12vfS9vP package main import "fmt" func main() { err := run()
我可以将三元条件运算符用于 if {} else {} 语句,如下所示:a ? x : y,还是问题?回答 1 : 回答 2。 是否可以使用这种格式来检查,而不是 a 是 true 还是 false,
无法弄清楚这里出了什么问题。按照设计设置说明,用谷歌搜索我能想到的一切,仍然没有运气。 undefined method `email' for # Extracted source (around
今天写一些 rspec 时,我遇到了一些意外的行为,将日期(和时间)实例与 nil 进行比较。这是一个使用原始 ruby 的示例(没有 Rails 或其他库): user@MacBook-Work
我将数据类型的非零值分配给非可选属性,然后将其分配给可选属性,最后用所述数据实例化图像。当可选项通过 if-let 子句时,它的 block 执行,抛出错误: Fatal error: Unexpec
swift 5.1 。 考虑以下。 let x: Any? = nil let y: Any = x print("x \(x)") // x nil pri
请耐心听我解释这一点, 我正在创建一个聊天室,用户可以在其中上传照片供其他人查看。当用户点击图标时,他们可以将照片上传到我的 Firebase 数据库(这已成功完成,我已经对此进行了测试)。照片的 U
我的 xCode 5.0 目前遇到一个奇怪的问题:一个对象在控制台中似乎为 nil,但同时它可以通过代码访问。 图 1:对象似乎为零 图2:NSLog(@"%@", imgDownloader) 的输
我有一个实现协议(protocol)的类,以便添加 3 个变量。我专门设置了图像变量,调试器显示该变量存在,但是在我打印它时在代码中显示为 nil,我的 if let 语句也认为该变量为 nil。 @
这个问题在这里已经有了答案: Swift 2 ( executeFetchRequest ) : error handling (5 个答案) 关闭 7 年前。 开始在 SWIFT 中学习编码,每次
两者 (not 'nil) 和 (not nil) 求值为T,那么'nil和nil有什么区别吗?那么 ''nil 呢?如果 ''nil 的计算结果为 'nil,那么 ''nil 是否也应该计算为 ni
(if '(nil nil) 'print-true 'print-false) (if '(nil) 'print-true 'print-false) 在上面的代码
这个问题在这里已经有了答案: 关闭 11 年前。 Possible Duplicate: obj.nil? vs. obj == nil 我发现了一个问题 - == nil 和 nil 哪个更好?
此代码段抛出异常: x = nil jsoned = x.to_json puts 'x.to_json=' + jsoned.inspect puts 'back=' + JSON.parse(js
基本上我有一个对象想要传递给前端。我在后端记录了它,它不是空的,但是在前端,当我提醒它时,它变成了空。 ... presentation := &presentationStruct { Obje
我创建了一个自定义错误类型来包装错误,以便在 Golang 中更轻松地进行调试。当有错误要打印时它可以工作,但现在它会引起 panic 。 Demo type Error struct { E
写一个符合我当前问题的标题有点难..我有一个 main() 函数,它使用另一个包 (database_sql) 中的函数。该函数初始化一个全局变量 sql.DB*。初始化后,变量不为nil,但是对于其
我是一名优秀的程序员,十分优秀!