[ACCEPTED]-How to convert NSArray to NSData?-iphone

Accepted answer
Score: 194

Use NSKeyedArchiver (which is the last sentence 12 of the post Garrett links):

NSData *data = [NSKeyedArchiver archivedDataWithRootObject:array];

Note that all 11 the objects in array must conform to the NSCoding protocol. If 10 these are custom objects, then that means 9 you need to read up on Encoding and Decoding Objects.

Note that this will 8 create a fairly hard-to-read property list 7 format, but can handle a very wide range 6 of objects. If you have a very simple array 5 (strings for instance), you may want to 4 use NSPropertyListSerialization, which creates 3 a bit simpler property list:

NSString *error;
NSData *data = [NSPropertyListSerialization dataFromPropertyList:array format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error];

There's also 2 an XML format constant you can pass if you'd 1 rather it be readable on the wire.

Score: 95

On a somewhat related note, here's how you 1 would convert the NSData back to an NSArray:

NSArray *array = [NSKeyedUnarchiver unarchiveObjectWithData:data]
Score: 3

I am not sure if this will help you, but 1 it's a link for a NSMutableArray to NSData.

Score: 3

I used this code.

 NSError *error;
 NSMutableData *jsonData = [[NSJSONSerialization dataWithJSONObject:yourDemoArray
                                                                   options:0 // Pass 0 if you don't care about the readability of the generated string
                                                                     error:&error] copy];

0

Score: 2

Swift :

let data = NSKeyedArchiver.archivedData(withRootObject: jsonArray)
print(data)

0

Score: 1

You can do this-

NSArray *array= [NSArray array];
NSData *dataArray = [NSKeyedArchiver archivedDataWithRootObject:array];

0

Score: 1

In iOS 9+ use this please:

NSArray *array = [[NSArray alloc] init];
NSData *data = [NSPropertyListSerialization dataWithPropertyList:array format:NSPropertyListBinaryFormat_v1_0 options:0 error:nil];

The older version 1 of this was deprecated in iOS 8.

Score: 0

Swift 5

let data = try! NSKeyedArchiver.archivedData(withRootObject: array, requiringSecureCoding: true)

0

More Related questions