代码之家  ›  专栏  ›  技术社区  ›  RK-

目标C中的关键值编码和关键值观察是什么?

  •  61
  • RK-  · 技术社区  · 15 年前

    有人能简单地解释一下什么是 Key-Value-Coding Key-Value-Observing ?请不要提供苹果开发者参考文件的链接。我已经经历过了。我希望有一个非常简单的解释。

    4 回复  |  直到 11 年前
        1
  •  116
  •   Darren    15 年前

    id someValue = [myObject valueForKeyPath:@"foo.bar.baz"];
    

    id someValue = [[[myObject foo] bar] baz];
    

    [myObject addObserver:self forKeyPath:@"foo.bar.baz" options:0 context:NULL];
    
        2
  •  28
  •   D.C.    15 年前

    // Here is a new instance of an object
    Foo *foo = [[Foo alloc] init];
    // Accessing a property called someValue with literal syntax:
    [foo someValue];
    // Accessing the same property with dot notation
    foo.someValue;
    // Accessing the same property with Key-Value coding:
    [foo valueForKey:@"someValue"];
    

        3
  •  12
  •   uliwitness    11 年前

    NSNumber* foo = [myPopup valueForKey: @"selectedItemIndex"];
    [myPopup setValue: @15 forKey: @"selectedItemIndex"];
    

    void*    gMyKVOContext = &gMyKVOContext; // global variable somewhere that guarantees us a unique address that doesn't collide with a subclass's registration for observing the same property
    
    ...
    
    [interestingObject addObserver: interestedObject forKeyPath: @"interestingProperty" options: 0 context: gMyKVOContext];
    

    - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
    {
        if( context == gMyKVOContext && [keyPath isEqualToString: @"interestingProperty"] )
        {
            // Update UI that shows interestingProperty
        }
        else
            [super observeValueForKeyPath: keyPath ofObject: object change: change context: context];
    }
    

    -(void)  setFoo: (int)inFoo
    {
        [self willChangeValueForKey: @"foo"];
        _foo = inFoo;
        [self didChangeValueForKey: @"foo"];
    }
    

    -(void) setFoo: (int)inFoo bar: (int)inBar
    {
        [self willChangeValueForKey: @"foo"];
        [self willChangeValueForKey: @"bar"];
        _foo = inFoo;
        _bar = inBar;
        [self didChangeValueForKey: @"bar"];
        [self didChangeValueForKey: @"foo"];
    }
    

        4
  •  7
  •   Vebjorn Ljosa    11 年前