简体   繁体   中英

NSCell -stringValue calls -setStringValue?

In essence, here is my code in a subclass of NSTextFieldCell:

- (void)setStringValue:(NSString *)aString {
    [super setStringValue:aString];
    [self doSomething];
}

- (void)doSomething {
    NSLog(@"%@", [self stringValue]);
}

In essence, I'm trying to get my subclass notified of a change in the string value, and when the value changes, I want the subclass of NSCell to be able to do something with that new value (Using -attributedStringValue would be even better, because I want to cache it for special drawing). The problem is, for some reason, calling -(NSString *)stringValue somehow results in a call to -(void)setStringValue which ends up becoming...

...an infinite loop. Can someone enlighten me on this - and a possible workaround?

Probably stringValue is doing some lazy initialization. If it detects that it has no stringValue but can derive the value from something else (perhaps attributedStringValue ?), then it derives the value, calls [self setStringValue:derivedValue] , then returns the value.

This does make life tricky, though. Try something like this?

@implementation MyCell ()
{
    BOOL gettingStringValue;
}
@end

- (NSString*)stringValue {
    gettingStringValue = YES;
    NSString* stringValue = [super stringValue];
    gettingStringValue = NO;
    return stringValue; 
}

- (void)setStringValue:(NSString *)aString {
    [super setStringValue:aString];
    if (!gettingStringValue)
        [self doSomething];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM