我正在尝试在 cocoa 中实现一个简单的对象桥,其中该桥对象充当其他任意NSObject实例的kvo/bindings兼容对象。

这是我的问题(下面的代码中有更多详细信息):

桥对象充当一个Person-Object的放置,具有一个名为name的NSString *属性和一个Address *属性地址。绑定(bind)到Bridge的keyPath“名称”或“地址”可以很好地工作。将某些对象绑定(bind)到网桥的keyPath“address.street”并为Person的address属性设置一个新的Address-Object时,故障开始。这导致与KVO相关的异常如下所示:



即使网桥注意到“地址”-属性中的更改并发出willChangeValueForKeyPath/didChangeValueForKeyPath元组,也会发生这种情况。

下面的代码产生了问题。它是独立的objective-c代码,可以保存在文件“BridgeDemo.m”中,并与

gcc -o test BridgeDemo.m -framework AppKit -framework Foundation; ./test

如果您知道该问题的解决方案,或者可以为我提供更好的解决同一问题的方法,那么您会让我成为非常的程序员!

BridgeDemo.m:
#import <Foundation/Foundation.h>
#import <AppKit/AppKit.h>

/* --- Address ----------------------------------------- */

@interface Address : NSObject {
    NSString* street;
    NSNumber* zipCode;
    NSString* city;
}

@property(retain) NSString* street;
@property(retain) NSNumber* zipCode;
@property(retain) NSString* city;

@end

@implementation Address

@synthesize street, zipCode, city;

-(id)init {
    if( !( self = [super init] ) ) { return nil; }

    self.street  = @"Elm Street";
    self.zipCode = @"12345";
    self.city    = @"Crashington";

    return self;
}

-(void) modifyStreet {
    self.street = @"Main Street";
}

-(void)dealloc {
    [street release]; [zipCode release]; [city release];
    [super dealloc];
}
@end

/* --- Person ----------------------------------------- */

@interface Person : NSObject {
    NSString* name;
    Address* address;
}
@property(retain) NSString* name;
@property(retain) Address* address;
@end

@implementation Person

@synthesize address, name;

-(id)init {
    if( !( self = [super init] ) ) { return nil; }

    self.name = @"Tom";
    self.address = [[Address new] autorelease];

    return self;
}

- (void)modifyAddress {
    Address* a = [[Address new] autorelease];
    a.street  = @"Jump Street";
    a.zipCode = @"54321";
    a.city    = @"Memleakville";
    self.address = a;
}

- (void)dealloc { [address release]; [name release]; [super dealloc]; }

@end

/* --- Bridge ----------------------------------------- */

@interface Bridge : NSObject {
    NSMutableDictionary* observedKeys;
    NSObject* obj;
}

@property(retain) NSObject* obj;

@end

@implementation Bridge

@synthesize obj;

- (id)init {
    if( !( self = [super init] ) ) { return nil; }
    observedKeys = [NSMutableDictionary new];
    return self;
}
- (void)forwardInvocation:(NSInvocation*)inv {
    [inv invokeWithTarget:obj];
}

- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector {
    return [obj methodSignatureForSelector:aSelector];
}

- (void) observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    NSLog( @">>>> Detected Change in keyPath: %@", keyPath );
    [self willChangeValueForKey:keyPath];
    [self didChangeValueForKey:keyPath];
}

-(id)valueForUndefinedKey:(NSString*)key {
    /* Register an observer for the key, if not already done */
    if( ![observedKeys objectForKey:key] ) {
        [observedKeys setObject:[NSNumber numberWithBool:YES] forKey:key];
        [obj addObserver:self forKeyPath:key options:NSKeyValueObservingOptionNew context:nil];
    }
    return [obj valueForKey:key];
}

- (void)dealloc {
    for( NSString* key in [observedKeys allKeys] ) {
        [obj removeObserver:self forKeyPath:key];
    }
    [obj release];
    [observedKeys release];
    [super dealloc];
}

@end

/* --- MyObserver ------------------------------------ */

@interface MyObserver : NSObject {
    Address* address;
    NSString* street;
}

@property(retain) Address* address;
@property(retain) NSString* street;
@end

@implementation MyObserver

@synthesize street, address;

-(void)dealloc { [street release]; [super dealloc]; }

@end


/* This works fine */
void testBindingToAddress() {
    NSLog( @"Testing Binding to 'address' --------------" );
     NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
    Bridge* b = [[Bridge new] autorelease];
    b.obj = [Person new];
    MyObserver* o = [[MyObserver new] autorelease];
    [o bind:@"address" toObject:b withKeyPath:@"address"
        options:nil];
    NSLog( @"Before modifyStreet: %@", o.address.street );
    [[b valueForKey:@"address"] performSelector:@selector(modifyStreet)];
    NSLog( @"After modifyStreet: %@", o.address.street );

    [b performSelector:@selector(modifyAddress)];
    NSLog( @"After modifyAdress:  %@", o.address.street );

    [pool drain];
}

/* This produces an exception */
void testBindingToStreet() {
    NSLog( @"Testing Binding to 'address.street' --------------" );
     NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
    Bridge* b = [[Bridge new] autorelease];
    b.obj = [Person new];
    MyObserver* o = [[MyObserver new] autorelease];
    [o bind:@"street" toObject:b withKeyPath:@"address.street"
        options:nil];

    NSLog( @"Before modifyStreet: %@", o.street );
    [[b valueForKey:@"address"] performSelector:@selector(modifyStreet)];
    NSLog( @"After modifyStreet: %@", o.street );

    [b performSelector:@selector(modifyAddress)];
    NSLog( @"After modifyAdress:  %@", o.street );

    [pool drain];
}

/* --- main() ------------------------------------ */
int main (int argc, const char * argv[]) {
    testBindingToAddress();
    testBindingToStreet();
    return 0;
}

最佳答案

这是问题所在:

[self willChangeValueForKey:keyPath]; [self didChangeValueForKey:keyPath];
通过不提供新的值(value),您将使观察者失去退订的机会。

这是一个可以正常工作并演示该问题的被黑版本。

/* --- Bridge ----------------------------------------- */
....
.....

@interface Bridge : NSObject {
    NSMutableDictionary* observedKeys;
    NSObject* obj;

    //**** Dictionary for old values just before we send the didChangeValue notification.
    NSMutableDictionary * oldValues;
}

...
.....

- (id)init {
    if( !( self = [super init] ) ) { return nil; }
    observedKeys = [NSMutableDictionary new];
    //************* Initialize the new dictionary
    oldValues = [NSMutableDictionary new];
    return self;
}
....
.....

- (void) observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    NSLog( @">>>> Detected Change in keyPath: %@", keyPath );
    // ****  Cache the old value before telling everyone its going to change.
    [oldValues setValue:[change valueForKey:NSKeyValueChangeOldKey] forKey:keyPath];
    [self willChangeValueForKey:keyPath];
    // **** Simulate the change by removing the old value.
    [oldValues removeObjectForKey:keyPath];
    // **** Now when we say we did change the value, we are not lying.
    [self didChangeValueForKey:keyPath];
}

-(id)valueForUndefinedKey:(NSString*)key {
    // **** Important part, return oldvalue if it exists
    id oldValue;
    if(oldValue = [oldValues valueForKey:key]){
        return oldValue;
    }
    /* Register an observer for the key, if not already done */
    if( ![observedKeys objectForKey:key] ) {
        [observedKeys setObject:[NSNumber numberWithBool:YES] forKey:key];
        NSLog(@"adding observer for:%@", key);
        [obj addObserver:self forKeyPath:key options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:nil];
    }
    return [obj valueForKey:key];
}
....
......

关于cocoa - 用C实现符合KVO/Bindings的桥模式,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/204125/

10-09 16:31