上記のコードは問題ないようです。コードのどこかに問題があるのではないでしょうか? ここに、出発点として役立つかもしれない、私がすぐに生成したコードがありますか??
#import "MainViewController.h"
#import "Maintness.h"
@interface MainViewController ()
@property (weak, nonatomic) IBOutlet UITextField *type;
@property (weak, nonatomic) IBOutlet UITextField *serialNumber;
@property (strong, nonatomic) NSManagedObjectContext *context;
- (IBAction)addButtonPressed:(id)sender;
- (IBAction)retrieveButtonPressed:(id)sender;
@end
@implementation MainViewController
#pragma mark - lazy instantiation
- (NSManagedObjectContext *)context{
if (!_context){
id appDelegate = (id)[[UIApplication sharedApplication] delegate];
_context = [appDelegate managedObjectContext];
}
return _context;
}
#pragma mark - core data interactions
- (IBAction)addButtonPressed:(id)sender {
NSError *error = nil;
Maintness *newMaintness = nil;
newMaintness = [NSEntityDescription insertNewObjectForEntityForName:@"Maintness" inManagedObjectContext:self.context];
newMaintness.type = self.type.text;
newMaintness.serialNumber = self.serialNumber.text;
if (![self.context save:&error]) {
NSLog(@"Oh no - error: %@", [error localizedDescription]);
} else {
NSLog(@"It appears the details were added ok");
}
}
- (IBAction)retrieveButtonPressed:(id)sender {
NSError *error = nil;
// Set up fetch
NSFetchRequest *fetch = [[NSFetchRequest alloc] init];
// Set up entity
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Maintness" inManagedObjectContext:self.context];
[fetch setEntity:entity];
// Set up sorting
// - sorts in order of array
NSSortDescriptor *primarySortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"type" ascending:YES];
NSSortDescriptor *secondarySortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"serialNumber" ascending:NO];
NSArray *sortDescriptors = @[primarySortDescriptor, secondarySortDescriptor];
[fetch setSortDescriptors:sortDescriptors];
NSArray *results = [self.context executeFetchRequest:fetch error:&error];
for (Maintness *result in results) {
NSLog(@"type: %@ serial number: %@", result.type, result.serialNumber);
}
}
@end