在核心数据中搜索的问题

issues with Searching in Core Data

我正在使用这段代码来查找数据的存在。但我收到此错误,即使用未声明的标识符“appDelegate”。

- (IBAction)findContact:(id)sender {
CoreDataAppDelegate *appDelegate =
   [[UIApplication sharedApplication] delegate];

NSManagedObjectContext *context =
   [appDelegate managedObjectContext];

NSEntityDescription *entityDesc =
   [NSEntityDescription entityForName:@"Contacts"
   inManagedObjectContext:context];

NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:entityDesc];

NSPredicate *pred =
   [NSPredicate predicateWithFormat:@"(name = %@)",
    _name.text];
[request setPredicate:pred];
NSManagedObject *matches = nil;

NSError *error;
NSArray *objects = [context executeFetchRequest:request
    error:&error];

if ([objects count] == 0) {
   _status.text = @"No matches";
} else {
   matches = objects[0];
   _address.text = [matches valueForKey:@"address"];
   _phone.text = [matches valueForKey:@"phone"];
   _status.text = [NSString stringWithFormat:
       @"%lu matches found", (unsigned long)[objects count]];
}
}

我已经包含了 #import <CoreData/CoreData.h> 。我还需要包含一些其他文件吗?当我保存数据时它工作正常。

确保您已导入应用委托 header

#import "CoreDataAppDelegate.h"

尝试将 AppDelegate 转换为 CoreDataAppDeleage

CoreDataAppDelegate *appDelegate = (CoreDataAppDelegate*)[[UIApplication sharedApplication] delegate];
CoreDataAppDelegate *appDelegate =
   [[UIApplication sharedApplication] delegate];

将上一行替换为下一行

     AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];

用于删除基于 Id 的文本

#pragma mark - delete tracking details

- (void)deleteTrackingId:(NSString *)trackingId

    {
        appDelegate = [[UIApplication sharedApplication] delegate];
        managedObjectContext = appDelegate.managedObjectContext;
        NSError *error;

        NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
        NSEntityDescription *entityOne = [NSEntityDescription entityForName:@"TrackingList" inManagedObjectContext:managedObjectContext];

        [fetchRequest setEntity:entityOne];
        NSPredicate *predicate=[NSPredicate predicateWithFormat:@"trackingId == %@",trackingId];

        [fetchRequest setPredicate:predicate];
        NSArray *fetchedObjects = [managedObjectContext executeFetchRequest:fetchRequest error:&error];

        if (fetchedObjects == nil) {
            NSLog(@"Could not delete Entity Objects");
        }

        for (TrackingList *trackingObject in fetchedObjects) {
            [managedObjectContext deleteObject:trackingObject];
        }

        [appDelegate saveContext];
    }