我正在使用这段代码来查找数据的存在。但是我收到了使用未声明标识符“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>
。我是否必须包含其他一些文件。当我保存数据时,它工作正常。
答案 0 :(得分:0)
确保您已导入应用委托标题
#import "CoreDataAppDelegate.h"
尝试将AppDelegate强制转换为CoreDataAppDeleage
CoreDataAppDelegate *appDelegate = (CoreDataAppDelegate*)[[UIApplication sharedApplication] delegate];
答案 1 :(得分:0)
CoreDataAppDelegate *appDelegate =
[[UIApplication sharedApplication] delegate];
将上一行替换为下一行
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
答案 2 :(得分:0)
用于删除基于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];
}