不同类中2个属性之间的Cocoa绑定

不同类中2个属性之间的Cocoa绑定,cocoa,binding,cocoa-bindings,Cocoa,Binding,Cocoa Bindings,我学习cocoa大约两周,目前我正在尝试理解绑定,我可以将2个非UI属性绑定在一起吗 我尝试通过编程方式绑定它们,但似乎无法使其正常工作 [ClassA bind: @"property1" toObject: ClassB // <--------Error here withKeyPath:@"propert2" options:bindingOptions]; [ClassA绑定:@“property1” toObject:ClassB/是-

我学习cocoa大约两周,目前我正在尝试理解绑定,我可以将2个非UI属性绑定在一起吗

我尝试通过编程方式绑定它们,但似乎无法使其正常工作

[ClassA bind: @"property1"
       toObject: ClassB // <--------Error here 
    withKeyPath:@"propert2"
        options:bindingOptions];
[ClassA绑定:@“property1”
toObject:ClassB/是--将任意属性绑定到另一个属性是完全有效的。这在自动更新UI时通常很有用,这就是为什么Apple的许多示例展示用户界面元素属性的原因。但是绑定并不以任何方式局限于UI对象。具体示例见下文:

//
//  AppDelegate.m
//  StackOverflow
//
//  Created by Stephen Poletto on 10/15/11.
//

#import "AppDelegate.h"

@interface ClassA : NSObject {
    NSString *propertyA;
}

@property (copy) NSString *propertyA;

@end

@interface ClassB : NSObject {
    NSString *propertyB;
}

@property (copy) NSString *propertyB;

@end

@implementation ClassA
@synthesize propertyA;
@end

@implementation ClassB
@synthesize propertyB;
@end

@implementation AppDelegate

@synthesize window = _window;

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
    ClassA *a = [[ClassA alloc] init];
    ClassB *b = [[ClassB alloc] init];

    [a bind:@"propertyA" toObject:b withKeyPath:@"propertyB" options:nil];

    // Now that the binding has been established, if propertyB is set on 'b',
    // propertyA will automatically be updated to have the same value.
    [b setPropertyB:@"My Message"];
    NSLog(@"A's propertyA: %@", [a propertyA]); // Prints 'MyMessage'. Success!
}

@end

请注意,bind:是在类的实例上调用的,而不是在类本身上调用的。如果您是Cocoa新手,您应该知道绑定是比较难的概念之一,在使用它们之前,您应该确保您了解KVC和KVO。

老实说,如果您只学了两周Cocoa,那么我会暂时忘记绑定先学会用“艰难的方式”做每件事。