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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…