3

OK, here we are :

  • I've got an NSTextView
  • I'm getting it's NSMutableAttributedString content
  • I'm unable to read/write it to plist

By using Rob's code ( Saving custom attributes in NSAttributedString ), I've made some progress (I'm managing to write the data to disk), but I cannot recover it (= NSKeyedUnarchiver returns nil).


Encoding :

// where MAS --> NSMutableAttributedString

NSData* stringData = [NSKeyedArchiver archivedDataWithRootObject:MAS];

Decoding :

NSMutableAttributedString* mas = (NSMutableAttributedString*)[NSKeyedUnarchiver unarchiveObjectWithData:dat];

Any ideas? Any possible workaround (even if not with NSCoder, which I doubt it works with RTFs...) would be welcome!

Community
  • 1
  • 1
Dr.Kameleon
  • 22,532
  • 20
  • 115
  • 223
  • 1
    As a note unarchiving/deserializing objects generally results in an immutable copy. – Joe Sep 10 '12 at 16:59
  • Can you not just use NSData's writeToFile:atomically: to write it and then dataWithContentsOfFile to read it back in? – Mark Sep 10 '12 at 17:09
  • @mark OK, I will; and *how* do I convert my `NSData` back to `NSAttributedString`? – Dr.Kameleon Sep 10 '12 at 17:10
  • Ah, I see your point. Let me think. – Mark Sep 10 '12 at 17:18
  • @mark Unfortunately, it's not an issue with saving per se; but with archiving/unarchiving and deserialization :/ – Dr.Kameleon Sep 10 '12 at 17:19
  • I think @Joe may have a point. Try using NSMutableAttributedString's initWithAttributedString: method instead of typecasting. – Mark Sep 10 '12 at 17:21
  • @mark He's right; I've already corrected that. But it's still far from the solution... – Dr.Kameleon Sep 10 '12 at 17:25
  • Question, does this solution http://stackoverflow.com/questions/2626667/saving-custom-attributes-in-nsattributedstring work as long as you are using NSAttributedString instead of NSMutableAttributedString? – Mark Sep 10 '12 at 17:28
  • @mark Well, not actually; this is exactly the one I've studied most... (and partially copied)... but nope. – Dr.Kameleon Sep 10 '12 at 17:30

1 Answers1

5

And here's how it was solved.

NSAttributedString -> NSData :

NSData* j = [(NSMutableAttributedString*)MAS RTFDFromRange:NSMakeRange(0,[[MAS string] length]) 
                                        documentAttributes:nil];

NSData -> NSAttributedString

NSMutableAttributedString* mas = [[NSMutableAttributedString alloc] initWithRTFD:dat 
                                                              documentAttributes:nil];

Simple as that.

Dr.Kameleon
  • 22,532
  • 20
  • 115
  • 223