【问题标题】:Cocoa: bind to composite object and observe child propertiesCocoa:绑定到复合对象并观察子属性
【发布时间】:2013-02-01 12:36:25
【问题描述】:

是否可以绑定到自定义对象并在该对象的特定属性发生更改时得到通知?

例子:

每个销售代表对象都有一个对销售统计对象的引用,该对象包含汽车和卡车销售的统计数据。自定义 NSView 用于在一个图形中绘制汽车和卡车销售。

自定义视图需要访问完整的统计对象,所以我将它绑定到salesRep.salesStats

但是,当我更改 carSales 属性时,我需要一种更新视图的方法。目前它没有更新,因为它绑定到父对象。

我想避免为每种销售类型建立绑定(这只是一个示例,我的具体情况更复杂)。

@interface SBSalesRep : NSObject {

@property (strong) SBSalesStatistics *salesStats;
}

@interface SBSalesStatistics : NSObject
{
@property (assign) NSInteger carSales;
@property (assing) NSInteger truckSales;
}

@interface SBProgressView : NSView
{
@property (strong) SBSalesStatistics *statsToDisplay;
}

// Setup
SBSalesRep *salesRep = [SBSalesRep new];

// Bind to stats object, because we need car and tuck sales:
[progressView bind:@"statsToDisplay" 
          toObject:salesRep 
       withKeyPath:@"salesStats"  // How to get notified of property changes here?
           options:nil];

// This needs to trigger an update in the statistics view
salesRep.salesStats.carSales = 50;

// I tried this, but it does not work:
[salesRep willChangeValueForKey:@"salesStatistics"];
salesRep.salesStats.carSales = 50;
[salesRep didChangeValueForKey:@"salesStatistics"];

【问题讨论】:

    标签: objective-c cocoa cocoa-bindings key-value-observing


    【解决方案1】:

    你说:

    // I tried this, but it does not work:
    [salesRep willChangeValueForKey:@"salesStatistics"];
    salesRep.salesStats.carSales = 50;
    [salesRep didChangeValueForKey:@"salesStatistics"];
    

    我的猜测是这不起作用,因为您要通知的密钥是 salesStatistics,但您要绑定的密钥是 salesStats。如果这些键相同,我希望这种方法可以工作。

    除此之外,更好的方法可能是添加这样的依赖项:

    @implementation SBSalesRep
    
    + (NSSet *) keyPathsForValuesAffectingSalesStats
    {
        return [NSSet setWithObjects: @"salesStats.carSales", @"salesStats.truckSales", nil];
    }
    
    @end
    

    这将导致对键 salesStats 的任何观察(绑定或其他方式)也隐式观察 salesStats.carSalessalesStats.truckSales,并且应该达到预期的效果,而无需使用 -will/didChangeValueForKey: 手动通知。

    【讨论】:

    • 非常感谢!使用关键路径是我缺少的部分。
    猜你喜欢
    • 1970-01-01
    • 2021-11-22
    • 2017-07-12
    • 1970-01-01
    • 2020-06-05
    • 1970-01-01
    • 1970-01-01
    • 2015-02-06
    • 1970-01-01
    相关资源
    最近更新 更多