对于随后的新闻感到抱歉。非常感谢您的耐心等待。
向核心数据添加新对象时,正确的初始值设定为:
- (id)initWithEntity:(NSEntityDescription *)entity insertIntoManagedObjectContext: (NSManagedObjectContext *)context
好的,所以我理解的是initWithEntity部分。我的核心数据模型中只有一个实体,所以我把它放在那里。上下文是我困惑的地方。首先,在哪里声明上下文,还是我甚至需要声明它?简单地输入self.ManagedObjectContext不起作用,也不自动完成。也许是因为我试图从我的AddViewController调用这个方法是原因,所以即使我输入Car.ManagedObjectContext或AppDelegate.ManagedObjectContext也会发生同样的事情。我猜我可以在我的care-data生成的模型类(Car.h)中声明它,但它实际上做了什么?
我在这里不理解什么?对不起,对于新问题。我真的一直试图解决这个问题几个小时。
这是我的代码。
car.h:
@interface Car : NSManagedObject
@property (nonatomic, retain) NSString * brand;
@property (nonatomic, retain) NSString * model;
@property (nonatomic, retain) NSString * year;
@property (nonatomic, retain) NSString * color;
@property (nonatomic, retain) NSNumber * engineSize;
@property (nonatomic, retain) NSNumber * weight;
@property (nonatomic, retain) id image;
@end
car.m:
#import "Car.h"
@implementation Car
@dynamic brand;
@dynamic model;
@dynamic year;
@dynamic color;
@dynamic engineSize;
@dynamic weight;
@dynamic image;
@end
addViewController.h(不包括AppDelegate,因为它几乎都是标准的,似乎工作正常。我所做的所有编码都在addview控制器中):
#import <Cocoa/Cocoa.h>
@interface AddViewController : NSWindowController{
}
@property (weak) IBOutlet NSTextField *brandField;
@property (weak) IBOutlet NSTextField *modelField;
@property (weak) IBOutlet NSTextField *yearField;
@property (weak) IBOutlet NSTextField *weightField;
@property (weak) IBOutlet NSTextField *engineSizeField;
@property (weak) IBOutlet NSTextField *colorField;
@property (weak) IBOutlet NSImageView *imageField;
- (IBAction)saveCar:(id)sender;
@end
AddViewController.m:
#import "AddViewController.h"
#import "AppDelegate.h"
#import "Car.h"
@interface AddViewController ()
@end
@implementation AddViewController
@synthesize brandField;
@synthesize modelField;
@synthesize yearField;
@synthesize engineSizeField;
@synthesize weightField;
@synthesize colorField;
@synthesize imageField;
- (id)initWithWindow:(NSWindow *)window
{
self = [super initWithWindow:window];
if (self) {
// Initialization code here.
}
return self;
}
- (void)windowDidLoad
{
[super windowDidLoad];
// Implement this method to handle any initialization after your window controller's window has been loaded from its nib file.
}
- (IBAction)saveCar:(id)sender {
NSManagedObjectContext *context = [Car managedObjectContext]; //This doesn't work here "no known class method"
Car *newCar = [[Car alloc] initWithEntity:@"Car" insertIntoManagedObjectContext:Car.managedObjectContext]; //compiler complains about this, property not found.
newCar.brand = [brandField stringValue];
newCar.model = [modelField stringValue];
newCar.year = [yearField stringValue];
newCar.weight = [weightField objectValue];
newCar.engineSize = [engineSizeField objectValue];
newCar.color = [colorField stringValue];
newCar.image = imageField;
}
@end