views:

989

answers:

3

I have an NSAttributedString s and an integer i and I'd like a function that takes s and i and returns a new NSAttributedString that has a (stringified) i prepended to s.

It looks like some combination of -stringWithFormat:, -initWithString:, and -insertAttributedString: would do it but I'm having trouble piecing it together without a lot of convolution and temporary variables.

More generally, pointers to guides on making sense of NSAttributedString and NSMutableAttributedString would be awesome.

+3  A: 

Pointers here: Attributed Strings Programming Guide

The brief answer is use NSMutableAttributedString -- since it inherits from NSAttributedString, you can use it anywhere you'd use an (immutable) NSAttributedString.

A newly created NSMAS can slurp up the contents and attributes of an NSAS with the setAttributedString: method. You're then free to replaceCharactersInRange: or deleteCharactersInRange: or insertAttributedString: atIndex: to yours heart's content.

jm
+2  A: 

I think I found another way:

// convert it to a mutable string
NSMutableAttributedString *newString = [[NSMutableAttributedString alloc] initWithAttributedString:oldString];

// create string containing the number
NSString *numberString = [NSString stringWithFormat:@"%i", i];

// append the number to the new string
[newString replaceCharactersInRange:NSMakeRange([newString length] - 1, 0) withString:numberString];

I think this works because Apple's Documentation says:

- (void)replaceCharactersInRange:(NSRange)aRange withString:(NSString *)aString

The new characters inherit the attributes of the first replaced character from aRange. Where the length of aRange is 0, the new characters inherit the attributes of the character preceding aRange if it has any, otherwise of the character following aRange.

Georg
This works! Except it should be NSMakeRange(0,0) for prepending. Thanks!
dreeves
Well, definitely time to sleep, I can't read properly anymore. :)
Georg
+1  A: 

Here's a one-liner for it, thanks to the friendly people on the adium developers' IRC channel. It takes an NSAttributedString s and an integer i.

return [[[NSMutableAttributedString alloc] 
         initWithString:[NSString stringWithFormat:@"%i %@", i, [s string]]]
        autorelease];
dreeves