次の新しさでごめんなさい。ご理解のほどよろしくお願いいたします。
コアデータに新しいオブジェクトを追加する場合、正しい初期化子は次のとおりです。
- (id)initWithEntity:(NSEntityDescription *)entity insertIntoManagedObjectContext: (NSManagedObjectContext *)context
さて、私が理解しているinitWithEntityの部分です。コアデータモデルにはエンティティが1つしかないので、そこに配置します。文脈は私が混乱しているところです。まず、コンテキストをどこで宣言しますか、それとも宣言する必要がありますか?self.ManagedObjectContextと入力するだけでは機能せず、オートコンプリートも機能しません。AddViewControllerからこのメソッドを呼び出そうとしていることが理由である可能性があります。そのため、Car.ManagedObjectContextまたはAppDelegate.ManagedObjectContextと入力しても、同じことが起こります。ケアデータで生成されたモデルクラス(Car.h)で宣言できると思いますが、実際には何をしますか?
ここで何がわからないのですか?newbの質問でごめんなさい。私は本当に何時間もこれを理解しようとしてきました。
これが私のコードです。
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