问题描述
假设我们有 2 个实体:
-人物(姓名、年龄、..)
-房子(颜色)
我们用 @interface CutsomStackView : nsstackview
@property (nonatomic) NSView *viewA;
@property (nonatomic) NSView *viewB;
- (id)initWithFrame:(NSRect)frame views:(NSArray<NSView *> *)views;
@end
@implementation CutsomStackView
- (id)initWithFrame:(NSRect)frame views:(NSArray<NSView *> *)views
{
if (!(self = [super initWithFrame:frame]))
return nil;
_viewA = views[0];
_viewB = views[1];
self.detachesHiddenViews = YES;
self.orientation = NSUserInterfaceLayoutOrientationVertical;
self.spacing = 0;
self.distribution = nsstackviewdistributionFill;
CGFloat viewAHeight = NSHeight(_viewA.frame);
[self addArrangedSubview:_viewA];
[self addArrangedSubview:_viewB];
_viewA.translatesAutoresizingMaskIntoConstraints = NO;
[_viewA setContentHuggingPriority:NSLayoutPriorityrequired forOrientation:NSLayoutConstraintOrientationVertical];
[_viewA.heightAnchor constraintEqualToConstant:topBarViewHeight].active = YES;
_viewB.translatesAutoresizingMaskIntoConstraints = NO;
[_viewB setContentHuggingPriority:NSLayoutPriorityDefaultLow forOrientation:NSLayoutConstraintOrientationVertical];
return self;
}
@end
为每个房子多次记录数据
我们想让房子里的所有人都涂成蓝色
我们如何获取这个?
我试过这个代码,但它得到了所有人
house.addToPeople (newPeople)
怎么做?
解决方法
试试这个功能。它的作用是获取所有 People 并创建一个包含所有结果的数组。
func getAllItems() -> [People]? {
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "People")
request.returnsObjectsAsFaults = false
do {
let result: NSArray = try context.fetch(request) as NSArray
return (result as? [People])!
} catch let error {
print("Errore recupero informazioni dal context \n \(error)")
}
return nil
}
如果您想按照特定条件(例如颜色)执行搜索,请在 request
后使用以下代码:
//Here i'm searching by index,if you need guidance for your case don't hesitate asking
request.predicate = NSPredicate(format: "index = %d",currentItem.index)
编辑:实际上上面的代码只是为了得到所有的人,如果你想根据房屋进行搜索,请执行以下操作:
func retrieve()-> [People]{
//Fetch all of the houses with a certain name
let houseRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "House")
houseRequest.predicate = NSPredicate(format: "name = %@","newName") //This seearch is by name
houseRequest.returnsObjectsAsFaults = false
do {
//put the fetched items in an array
let result: NSArray = try context.fetch(houseRequest) as NSArray
let houses = result as? [Houses]
//Get the people from the previous array
let people: [People]? = (houses.people!.allObjects as! [People])
return people
} catch let error {
print("Errore recupero informazioni dal context \n \((error))")
}
return nil
}
,
感谢您的回答!
在这个例子中,“houses”是一个数组,所以我们必须添加一个索引 ➔ houses[0].people!.AllObjects
非常感谢您的解释。