gpt4 book ai didi

ios - 按名称获取实体并使用 CoreData 创建关系

转载 作者:行者123 更新时间:2023-11-29 03:00:44 25 4
gpt4 key购买 nike

我正在尝试在两个实体 Mensagem 和 Category 之间创建关系,但出现以下错误:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Unacceptable type of value for to-many relationship: property = "mensagemParaCategorias"; desired type = NSSet; given type = __NSArrayI; ...
).'

我尝试做的是:创建一个实体属性(categoriaAtual),然后尝试按名称获取实体,并将实体设置为获取的结果,然后创建关系。

这是我的代码。

创建初始日期.h

#import <Foundation/Foundation.h>
#import "Mensagens.h"
#import "Categorias.h"

@interface createInitialData : NSObject

@property (strong, nonatomic) NSManagedObjectContext *managedObjectContext;
@property (nonatomic, strong) NSFetchedResultsController *fetchedResultsController;
@property (nonatomic) Categorias *categoriaAtual;

-(void)createMessage:(NSString *)mensagem ComAutor:(NSString *)autor;

创建初始数据.m

-(void)createMessage:(NSString *)mensagem ComAutor:(NSString *)autor {
Mensagens *novaMensagem = (Mensagens *)[NSEntityDescription insertNewObjectForEntityForName:@"Mensagens" inManagedObjectContext:self.managedObjectContext];

[novaMensagem setMensagem:mensagem];
[novaMensagem setAutor:autor];
NSDate *agora = [NSDate date];
[novaMensagem setDataCriada:agora];
[self categoria:@"Posts"];

novaMensagem.mensagemParaCategorias = _categoriaAtual; // This is where i try to create the relation between the 2 entities.

NSError *error = nil;
NSManagedObjectContext *context = self.managedObjectContext;

if (![context save:&error]) {
NSLog(@"Error! %@", error);
}

}



-(void)categoria:(NSString *)nomeCategoria {
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc]init];


NSEntityDescription *entity = [NSEntityDescription entityForName:@"Categorias" inManagedObjectContext:self.managedObjectContext];
[fetchRequest setEntity:entity];

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"categoria == '%@'", nomeCategoria];
[fetchRequest setPredicate:predicate];

NSError *error = nil;

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

if (fetchedObjects == nil) {
NSLog(@"Problem! %@", error);
} else {
NSLog(@"Objetos %@", fetchedObjects);
_categoriaAtual = fetchedObjects;
}

}

最佳答案

mensagemParaCategorias

是一对多关系,但您正在将指针分配给一个不是 NSSet 实例的对象。 Xcode 有一个选项可以在您的托管对象子类上生成方法,以将对象添加到一对多关系中。

关于ios - 按名称获取实体并使用 CoreData 创建关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23328806/

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