dreeves dreeves - 3 months ago 9
Objective-C Question

String munging in Objective-C with NSAttributedString

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.

Answer

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];