0

I have these 3 lines in code which are meant to take text from a .txt file and allocate it to an NSAttributedString

NSString *path = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"txt"];
NSString *text = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:NULL];

NSAttributedString *attString = [[NSAttributedString alloc] initWithString:text];

Using the debugger I know that the path is being found correctly, and the text is being added to the variable text fine, but its not converting to the NSAttributedString - the debugger just says "variable is not NSAttributedString"

What am I missing from the third line to allow the NSString to be converted to an NSSAttributedString? (I dont want any attributes, but Im presuming you can just load the string into an attributed string?)

3 Answers 3

1

The problem might come from somewhere else I guess, just tried :

NSString *path = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"txt"];
NSString *text = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:NULL];

NSAttributedString *attString = [[NSAttributedString alloc] initWithString:text];

NSLog(@"Text : %@\nNSAS : %@", text, attString);

Here is the output :

2013-06-10 11:17:04.444 TestsSO[5554:c07] Text : hello, world !
NSAS : hello, world !{
}

Are you sure that text is filled correctly ?

Sign up to request clarification or add additional context in comments.

4 Comments

Yes, in the debugger i can run the command po text and it gives the entire text file. It just doesnt seem to want to convert to an attributed string! im sure i just missing out a small detail but i cant figure out what it is!
Any special content in the file ? As I said, the code above works for me.
no, just basic text with a little bit of markup in it, which I presume is part of the NSUTF8 encoding - just the usual symbols included, nothing out of the ordinary
Could you try with a simple content like I did (hello, word !, for example) ?
0

try with

NSAttributedString *attString = [[NSAttributedString alloc] initWithString:text attributes:nil];

Hope it will work.

Comments

0

Try

NSMutableAttributedString *attri_str=[[NSMutableAttributedString alloc]initWithString:text];


  [attri_str addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"HelveticaNeue-Bold" size:15] range:NSMakeRange(0, 15)]; // Begin and Last letter

        [attri_str addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithRed:0/255.0 green:143/255.0 blue:255/255.0 alpha:0.75] range:NSMakeRange(0,25)];

I hope it help for you.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.