我在核心数据中有一个问题:
项目中有Books和Pages两个实体;Entity Books中有book用户创建的3个对象;Entity Pages中有page用户创建的多个对象;它们之间的关系是一个page属于一个book,一个book有多个页面。
我的问题是:有3个书具有相同的对象名“book”,并且每个书都有唯一的属性.bookName:@"metal" ;@"plastic" ;@"glass"。如何使用.bookName = @"glass"将page设置为book?
//In BookViewController
Books *book = (Books *)[NSEntityDescription insertNewObjectForEntityForName:@"Books" inManagedObjectContext:managedObjectContext];
//textView.text is user input text
book.bookName = textView.text;
//In PageViewController
Pages *page = (Pages *)[NSEntityDescription insertNewObjectForEntityForName:@"Pages" inManagedObjectContext:managedObjectContext];
page.itsbook = WHAT?感谢你的阅读,我在这里逗留了一天,真的很感谢你的帮助,爱你!
发布于 2010-12-01 02:04:06
如果你需要找到一本特定的书,那么你需要使用一个NSFetchRequest来请求核心数据。
需要相当多的代码,因此您可能会向Book类添加一个方便的方法,如下所示:
+(Book*)bookWithName:(NSString*)name
{
// 0. I assume you have something like this to get the context…
NSManagedObjectContext* context = [NSManagedObjectContext threadLocalContext];
// 1. Create an empty request
NSFetchRequest* request = [[[NSFetchRequest alloc] init] autorelease];
// 2. Set the entity description for the object to fetch
NSEntityDescription* entity = [NSEntityDescription entityForName:@"Book"
inManagedObjectContext:context];
[request setEntity:entity];
// 3. Set a predicate asking for objects with a mathing bookName property
NSPredicate* predicate = [NSPredicate predicateWithFormat:@"%K LIKE[cd] %@",
@"bookName",
name];
[request setPredicate:predicate];
// 4. Execute the request on the managed object context.
NSArray* objects = [context executeFetchRequest:request error:NULL];
// 5. Result is an array, maybe handle empty array and many objects?
return [objects lastObject];
}发布于 2010-11-30 21:44:30
我不明白你的意思。如果您想要插入一个页面作为书的子集,您需要下面这行代码:
[book addPageToBookObject:page]; // the method will be the relationship name如果您想从页面对象中获取图书,则需要一个从页面到图书的反向关系。
https://stackoverflow.com/questions/4314288
复制相似问题