gpt4 book ai didi

ios - 从 Core Data 中检索单个对象

转载 作者:行者123 更新时间:2023-12-01 17:55:34 24 4
gpt4 key购买 nike

在我的应用程序中,有多个画廊。所以我创建了一个名为 Gallery 的实体并插入了一些对象。像这样,

NSManagedObjectContext *context = [self managedObjectContext];

Gallery *gallery1 = [NSEntityDescription insertNewObjectForEntityForName:@"Gallery" inManagedObjectContext:context];
gallery1.galleryId = @1;
gallery1.galleryName = @"Art";
gallery1.galleryDesc = @"Some info about art";

Gallery *gallery2 = [NSEntityDescription insertNewObjectForEntityForName:@"Gallery" inManagedObjectContext:context];
gallery2.galleryId = @2;
gallery2.galleryName = @"Architecture";
gallery2.galleryDesc = @"details about architecture";

NSError *error;
if (![context save:&error]) {
NSLog(@"Error Ocurred When Saving: %@", error.localizedDescription);
}

现在在 View Controller 中,我需要根据所选画廊检索有关特定画廊的描述。

下面是我到目前为止的代码
NSFetchRequest *fetchRequst = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Gallery" inManagedObjectContext:self.managedObjectContext];
fetchRequst.entity = entity;
NSError *error;
// Gets the Gallery objects to an array
self.galleries = [self.managedObjectContext executeFetchRequest:fetchRequst error:&error];

// self.gallery is passed in to this view controller from the previous one
if ([self.gallery isEqualToString:@"Art"]) {
self.galleryInfoTextView.text = gallery.galleryDesc;
} else if ([self.gallery isEqualToString:@"Architecture"]) {
self.galleryInfoTextView.text = gallery.galleryDesc;
}

如何仅检索对象,例如 Art,然后显示其描述?

最佳答案

NSArray *galleryArray = [self.managedObjectContext executeFetchRequest:fetchRequst error:&error];


for (Gallery *gallery in galleryArray)
{
if(gallery.galleryName isEqualToString:@"Art"){
//this is gallery Object is of Art
} else if (gallery.galleryName isEqualToString:@"Architecture"){
//this is gallery Object is of Architecture
}
}

关于ios - 从 Core Data 中检索单个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18374440/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com