Giovanni
Giovanni

Reputation: 838

Appending NSAttributedStrings returns an error

Im following advice from answers to a previous question, but am recieving an error when running the following code, which is supposed to join an array of 5 strings into one larger string.

NSArray *myStrings = [text componentsSeparatedByString:@"//"];
NSMutableAttributedString *result = [[NSMutableAttributedString alloc] init];
NSAttributedString *delimiter = [[NSAttributedString alloc] initWithString:@","];

NSLog(@"The Content of myStrings is %@", myStrings);

for (NSAttributedString *str in myStrings)
{
    if (result.length)
    {
        [result appendAttributedString:delimiter];
    }

    [result appendAttributedString:str];
}

The printout from the NSLog returns:

2013-06-11 20:49:55.012 strings[11789:11303] The Content of myStrings is (
"Hello ",
"my name is ",
"Giovanni ",
"and im pretty crap ",
"at ios development"

So I know I have an array of 5 strings. However on the first run through the code, although it by-passes the 'if' loop (as it should), it throws an error on the final line in the 'for' loop:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFString string]: unrecognized selector sent to instance 0x716ec60'

I cant figure out why - both str and result are defined as the same type of string, so cant see why one cant be appended to the other. Any clues anybody?

Upvotes: 0

Views: 674

Answers (1)

Valent Richie
Valent Richie

Reputation: 5226

Seems your array contains NSString objects. NSAttributedString is not a subclass of NSString or vice versa. Both of them inherit from NSObject.

Before you append, try to create an instance of NSAttributedString with the method initWithString and pass str as the argument.

NSAttributedString *attributedString = [NSAttributedString initWithString:str];
[result appendAttributedString:attributedString];

And also the for loop needs to be updated:

for (NSString *str in myStrings) {
}

Upvotes: 3

Related Questions