May 23, 2004

NSTextStorage bug

Apple

This seems to be a well-known bug, but it took me three days of hunting to figure out what was going on :(

If you're trying to subclass the NSTextStorage class, you need to override one more method, in addition to the 4 methods described in Apple's documentation. The additional method is addAttribute:value:range::

- (void)addAttribute:(NSString *)name value:(id)value range:(NSRange)range;

Here is a simple NSTextStorage subclass that works in MacOS X 10.2, and hopefully in 10.3 as well:

@interface MyTextStorage : NSTextStorage {
  NSMutableAttributedString* string_;
}
@end

@implementation MyTextStorage

- initWithAttributedString:(NSMutableAttributedString*)string
{
  [super init];
  string_ = [string retain];
  return self;
}

- (void)dealloc {
  [[NSNotificationCenter defaultCenter] removeObserver:self];
  [string_ release];
  [super dealloc];
}

- (NSString*)string
{
  return [string_ string];
}

- (void)addAttribute:(NSString *)name value:(id)value range:(NSRange)range
{
  [string_ addAttribute:name value:value range:range];
}

- (NSDictionary *)attributesAtIndex:(unsigned)index effectiveRange:(NSRangePointer)range
{
  return [string_ attributesAtIndex:index effectiveRange:range];
}

- (void)setAttributes:(NSDictionary *)attrs range:(NSRange)range {
  [string_ setAttributes:attrs range:range];
}

- (void)replaceCharactersInRange:(NSRange)range withString:(NSString *)string
{
  int origLen = [self length];
  [string_ replaceCharactersInRange:range withString:string];
  [self edited:NSTextStorageEditedCharacters range:range changeInLength:[self length] - origLen];
}

@end

Update: This is strange. It looks like removing the call to [super init] in the -initWithAttributedString: method makes the system crash. The class works just fine with the super call, and the addAttribute:value:range: method definition removed. Really weird!

Posted by ovidiu at May 23, 2004 07:08 PM |
 
Copyright © 2002-2011 Ovidiu Predescu.