gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 16:38:31 25 4
gpt4 key购买 nike

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

我尝试以编程方式绑定(bind)它们,但似乎无法让它工作。

[ClassA bind: @"property1"
toObject: ClassB // <--------Error here
withKeyPath:@"propert2"
options:bindingOptions];

我想我可能会弄错,任何帮助或指导将不胜感激。

提前致谢,

问候,特伦斯

最佳答案

是的——将任意属性绑定(bind)到另一个属性是完全有效的。这在自动更新 UI 时通常很有用,这就是为什么 Apple 的许多示例都展示用户界面元素属性的原因。但绑定(bind)不以任何方式限制于 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 的新手,您应该知道绑定(bind)是较难的概念之一,并且在使用它们之前您应该确保您了解 KVC 和 KVO。

关于不同类中的 2 个属性之间的 Cocoa 绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7762851/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com