无法在NSManagedObject类中调用指定的初始化程序

时间:2014-04-17 15:22:00

标签: objective-c core-data nsmanagedobject nsmanagedobjectcontext

我正在构建一个简单的笔记应用程序并试图弄清楚如何使用我在数据模型部分创建的自定义类以及编辑/创建NSManaged对象子类。

由于我是初学者,如果你不介意我会发布我的.m文件(因为它真的很短),所以你可以抓住一些我做得不对的东西带来了这个错误:

Note.h :( .m文件中没有任何内容,目前我只处理内容道具)

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


@interface Note : NSManagedObject

@property (nonatomic, retain) NSString * noteID;
@property (nonatomic, retain) NSString * content;
@property (nonatomic, retain) NSDate * timeCreated;

@end

NotesListViewController.h:

    #import <UIKit/UIKit.h>

    @interface NONotesListViewController : UITableViewController

    - (IBAction) unwindToList:(UIStoryboardSegue *)segue;

    @end

#import "NONotesListViewController.h"
#import "Note.h"
#import "NOCreateNotesViewController.h"

@interface NONotesListViewController ()

@property (nonatomic, strong) NSMutableArray * notes;

@property NSInteger indx;

@end

@implementation NONotesListViewController

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


- (void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([segue.identifier isEqualToString:@"editeNote"]) {
        Note * selectedNote = [self.notes objectAtIndex:[self.tableView indexPathForSelectedRow].row];
        NOCreateNotesViewController * destination = [segue destinationViewController];
        destination.note = selectedNote;
        destination.isEdited = YES;
        self.indx = [self.tableView indexPathForCell:sender].row;
    }
}


- (IBAction) unwindToList:(UIStoryboardSegue *)segue
{
    NOCreateNotesViewController * source = [segue sourceViewController];

    Note * note = source.note;

    if (note != nil &&  source.isEdited == NO) {
        [self.notes addObject:note];
    } else {
        [self.notes replaceObjectAtIndex:self.indx withObject:note];
    }

    [self.tableView reloadData];
}


- (void)viewDidLoad
{
    [super viewDidLoad];

    self.notes = [[NSMutableArray alloc] init];

    NSManagedObjectContext * managedObjectContext = [self managedObjectContext];

    NSFetchRequest * fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"Note"];

    self.notes = [[managedObjectContext executeFetchRequest:fetchRequest error:nil] mutableCopy];

    [self.tableView reloadData];

}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    return self.notes.count;
}


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


    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

    // Configure the cell...

    Note * note = [self.notes objectAtIndex:indexPath.row];

    cell.textLabel.text = note.content;

    return cell;
}

@end

CreateNotesViewController.h:

#import <UIKit/UIKit.h>
#import "Note.h"

@interface NOCreateNotesViewController : UIViewController

@property (nonatomic, strong) Note * note;
@property BOOL isEdited;

@end

CreateNotesViewController.m:

#import "NOCreateNotesViewController.h"

@interface NOCreateNotesViewController ()

@property (weak, nonatomic) IBOutlet UITextView *noteText;

@property (weak, nonatomic) IBOutlet UIBarButtonItem *saveButton;

@end

@implementation NOCreateNotesViewController

- (NSManagedObjectContext *) managedObjectContext
{
    NSManagedObjectContext *context = nil;

    id delegate = [[UIApplication sharedApplication] delegate];

    if ([delegate performSelector:@selector(managedObjectContext)]) {
        context = [delegate managedObjectContext];
    }

    return context;
}


- (void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if (sender != self.saveButton) return;
    if (self.noteText.text.length > 0) {
        self.note = [[Note alloc] init];
        self.note.content = self.noteText.text;
    }

    NSManagedObjectContext * context = [self managedObjectContext];

    if (self.isEdited) {
        [self.note setValue:self.noteText.text forKey:@"content"];
    }

    NSManagedObject *newNote = [NSEntityDescription insertNewObjectForEntityForName:@"Note" inManagedObjectContext:context];

    [newNote setValue:self.noteText.text forKey:@"content"];

    NSError * error = nil;

    if ([context save:&error]) {
        NSLog(@"Can't Save! %@ %@", error, [error localizedDescription]);
    }
}


- (void)viewDidLoad
{
    [super viewDidLoad];

    // Do any additional setup after loading the view.
}

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


- (void)adjustViewForKeyboardReveal:(BOOL)showKeyboard notificationInfo:(NSDictionary *)notificationInfo
{
    // the keyboard is showing so ƒ the table's height
    CGRect keyboardRect = [[notificationInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    NSTimeInterval animationDuration =
    [[notificationInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    CGRect frame = self.noteText.frame;

    // the keyboard rect's width and height are reversed in landscape
    NSInteger adjustDelta = UIInterfaceOrientationIsPortrait(self.interfaceOrientation) ? CGRectGetHeight(keyboardRect) : CGRectGetWidth(keyboardRect);

    if (showKeyboard)
    frame.size.height -= adjustDelta;
    else
    frame.size.height += adjustDelta;

    [UIView beginAnimations:@"ResizeForKeyboard" context:nil];
    [UIView setAnimationDuration:animationDuration];
    self.noteText.frame = frame;
    [UIView commitAnimations];
}


- (void) viewWillAppear:(BOOL)animated
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}


- (void) keyboardWillShow:(NSNotification *)aNotification
{
    [self adjustViewForKeyboardReveal:YES notificationInfo:[aNotification userInfo]];
}


- (void) keyboardWillHide:(NSNotification *)aNotification
{
    [self adjustViewForKeyboardReveal:NO notificationInfo:[aNotification userInfo]];
}

我收到了这个错误:

enter image description here

1 个答案:

答案 0 :(得分:0)

您不能[[Note alloc] init],因为Note是NSManagedObject的子类。

指定的初始值设定项为awakeFromInsert:,在将对象插入managedObjectContext后调用。

如果您执行以下操作,则会调用它:

self.note = [Note [NSEntityDescription
    insertNewObjectForEntityForName:@"Note"
    inManagedObjectContext:self.managedObjectContext];

请参阅"Creating and Deleting Managed Objects" in the Core Data Programming guide

要清楚,您不应该手动为NSManagedObject创建子类。您将在xcdatamodeld文件中创建一个名为Note的实体,声明它由类Note表示,创建一个“Core Data”类型的新文件,该文件允许Xcode使用awakeFromInsert:函数原型正确创建类在里面。如果您开始编辑Note类,您需要查看MOGenerator工具。如果没有XCode创建类文件供您编辑,xcdatamodeld可能就足够了。