1

I have converted an NSArray to NSString using below code Suppose i have an array with some data in it.

NSString *sample=[array description];
NSLog(@"%@",sample);

which prints:

 (
    {
    URL = "1a516af1a1c6020260a876231955e576202bbe03.jpg##37911944cc1ea8fd132ee9421a7b3af326afcc19.jpg";
    userId = 0;
    wallpaperId = 31;
  },
    {
    URL = "a9356863fa43bc3439487198283321622f88e31f.jpg##f09c743ebdc26bb9f98655310a0529b65a472428.jpg";
    userId = 0;
    wallpaperId = 30;
    }
)

It looks like array but it is actually a string. Now I am wondering, how can I reconvert back to NSArray? Help appreciated.

And please this not a duplicate question, I couldn't found the same anywhere on SO.

Pankaj Wadhwa
  • 3,073
  • 3
  • 28
  • 37
  • 4
    do you need explicitly a `NSString`? Because if the purpose is to serialize the content of the array to be able to deserialize it later then using an `NSKeyedArchiver`/`NSKeyedUnarchiver` could be a better solution. Check this answer http://stackoverflow.com/questions/7743450/what-is-the-best-way-to-save-an-nsmutablearray-to-nsuserdefaults – Jack Aug 28 '14 at 12:45
  • 3
    Generally, `description` is not reversible. Use an archiver for serialization and un-archiver for deserialization. – Sergey Kalinichenko Aug 28 '14 at 12:45
  • 1
    Yep, use JSON or the archiver stuff. Don't use `description` except for debugging messages. – Hot Licks Aug 28 '14 at 12:48
  • actually i need to save that array to DB in a single field thats why i am converting it to string to save it in DB and while fetching i will reconvert it back to NSArray – Pankaj Wadhwa Aug 28 '14 at 12:51
  • @Jack i think you are right, i will try your way too. +1 – Pankaj Wadhwa Aug 28 '14 at 12:57

2 Answers2

5

You cannot rely on the results of description as it is not a convert to string operator, but merely a debugging aid. There is nothing to stop it changing between O/S releases and there is no equivalent fromDescription method.

The conventional way of serializing an Objective-C collection to and from a string is to use JSON, so look at the NSJSONSerialization class.

trojanfoe
  • 120,358
  • 21
  • 212
  • 242
  • I was wondering whether i should do this way or not but i think its a good idea to convert an array to JSON and then its easy to convert it back to array. +1 – Pankaj Wadhwa Aug 28 '14 at 13:00
-1

the

NSString componentsseparatedbystring

method will return an array of components separated by a string