iphone - 核心数据一对多关系
<p><p>我的核心数据模型中有一对多的关系。一餐可以有多种食物。我想用一顿饭的食物填满一张 table 。因此,如果第一餐有苹果、橙子和柠檬,那么餐 table 将由这三种食物组成。</p>
<p>非常感谢任何帮助,因为我完全陷入困境。</p>
<p>这是我的模型:</p>
<p> <img src="/image/OX4Cv.png" alt="enter image description here"/> </p>
<p>还有 NSManagedObject 类:</p>
<p>Meal.h</p>
<pre><code>@class Food;
@interface Meal : NSManagedObject
@property (nonatomic, retain) NSString *name;
@property (nonatomic, retain) NSSet *foods;
@end
@interface Meal (CoreDataGeneratedAccessors)
- (void)addFoodsObject:(Food *)value;
- (void)removeFoodsObject:(Food *)value;
- (void)addFoods:(NSSet *)values;
- (void)removeFoods:(NSSet *)values;
@end
</code></pre>
<p>食物.h</p>
<pre><code>@class Meal;
@interface Food : NSManagedObject
@property (nonatomic, retain) NSString * name;
@property (nonatomic, retain) Meal *meals;
@end
</code></pre>
<p>这是我尝试尝试的代码,但我遇到了一些问题。</p>
<pre><code>- (NSFetchedResultsController *)fetchedResultsController
{
if (_fetchedResultsController != nil)
return _fetchedResultsController;
NSFetchRequest *fetchRequest = [ init];
NSEntityDescription *entity = ;
;
];
NSSortDescriptor *sort = [ initWithKey:@"name" ascending:NO];
];
;
NSFetchedResultsController *theFetchedResultsController = [ initWithFetchRequest:fetchRequest managedObjectContext:_context sectionNameKeyPath:nil cacheName:@"Root"];
self.fetchedResultsController = theFetchedResultsController;
_fetchedResultsController.delegate = self;
;
;
return _fetchedResultsController;
}
</code></pre></p>
<br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
<p><p>您提到您遇到了问题,但没有提到问题是什么;但是您的 <code>NSFetchRequest</code> 谓词对我来说看起来不正确。此外,<code>Food</code> 上定义的 <code>meals</code> 是复数,但关系是一对一的——有点困惑。</p>
<p>您的 UITableView 应该填充单个 <code>Meal</code> 中的 <code>Food</code>,对吗?我们称它为 <code>Meal</code> <code>_thisMeal</code>,那么 fetch 谓词应该是:</p>
<pre><code>NSPredicate *foodPredicate = ;
;
</code></pre>
<p>所以,您要获取的实体是 <code>Food</code>;这个谓词确保他们的 <code>meals</code> 属性是你的 UITableViewController 正在寻找的 <code>Meal</code>。</p>
<p>更新以显示如何获取命名的 <code>Meal</code></p>
<p>要获取名为“Custom Meal”的<code>Meal</code>:</p>
<pre><code>Meal *_thisMeal = nil;
// this assumes that there should be only one Meal named "Custom Meal"
NSFetchRequest *request = [ initWithEntityName:@"Meal"];
NSPredicate *fetchPredicate = ;
NSError *fetchError = nil;
NSArray *meals = ;
if( fetchError )
NSLog(@"%s - ERROR while fetching Meal: %@,%@",__FUNCTION__,fetchError,);
else if( != 0 )
_thisMeal = ;
</code></pre></p>
<p style="font-size: 20px;">关于iphone - 核心数据一对多关系,我们在Stack Overflow上找到一个类似的问题:
<a href="https://stackoverflow.com/questions/9695031/" rel="noreferrer noopener nofollow" style="color: red;">
https://stackoverflow.com/questions/9695031/
</a>
</p>
页:
[1]