是 - 它是完全有效的任意屬性綁定到另一個屬性。這在自動更新用戶界面時非常有用,這就是爲什麼許多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之前瞭解它們。
說實話,如果你只學了兩個星期就可以學習可可,那麼我會忘記綁定一點點,並學會先把所有事情都做到「硬道路」。 –