Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

iphone - NSArray to Description and vice versa

I have NSMutableArray like :

NSMutableArray *x=[[NSMutableArray alloc]initWithObjects:@"a",@"b",@"c",@"d", nil];
NSLog(@"%@",x.description);

From the description I got the following result :

(
    a,
    b,
    c,
    d
)

I want to again recreate the array from the description is it possible ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

There is no way that would reliably work in all cases. For example, you cannot know if

(
    123
)

represents an array containing a string or a number.

Added: There actually is a method to convert the description back to an array object (but it does not always return an identical array for the reason given above). The description method of NSArray and NSDictionary uses the Old-Style ASCII Property Lists format which can be read using NSPropertyListSerialization:

NSArray *a1 = @[@"123", @456];
NSString *desc = [a1 description];

NSData *d = [desc dataUsingEncoding:NSUTF8StringEncoding];
NSArray *a2 = [NSPropertyListSerialization propertyListWithData:d
                                                        options:0
                                                         format:NULL
                                                          error:NULL];
NSLog(@"%@", a2);
NSLog(@"a1[1] is a %@", [a1[1] class]);
NSLog(@"a2[1] is a %@", [a2[1] class]);

Output:

(
    123,
    456
)
a1[1] is a __NSCFNumber
a2[1] is a __NSCFString

As you can see, the array a2 looks like a1, but the second element 456, which was a NSNumber originally, has been read back as a NSString.

So you should use description only as a debugging tool. Better methods to create a reversible human-readable description or an archive have been mentioned in the other answers and comments.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...