2011-10-14 82 views
2

我在學習可可時大約2個星期,目前我正試圖理解綁定,我可以將2個非UI屬性綁定在一起嗎?可可在2個屬性不同類別之間的綁定

我嘗試以編程方式綁定它們,但似乎無法使其工作。

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

我想我可能會把它弄錯,所有的幫助或方向將不勝感激。

預先感謝,

問候, 特倫斯

+1

說實話,如果你只學了兩個星期就可以學習可可,那麼我會忘記綁定一點點,並學會先把所有事情都做到「硬道路」。 –

回答

2

是 - 它是完全有效的任意屬性綁定到另一個屬性。這在自動更新用戶界面時非常有用,這就是爲什麼許多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之前瞭解它們。

相關問題