Mailing Lists: Apple Mailing Lists
Image of Mac OS face in stamp
Re: NSMutableArray to NSData
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: NSMutableArray to NSData

Le dimanche 6 janvier 2002, ` 03:45 , email@hidden a icrit :

Hello again.

Quick question: I need to convert NSMutableArray into an NSData object. I am planning to do that my writing the NSMutableArray to a file in /tmp and then reading the contents of the file in the NSData. Finally I will unlink the /tmp file.

This is a pretty stupid approach to solving my problem. Is there anything better out there?

If you just want to encode the array, that is, the pointers, but not the objects themselves, you can use the following code:

@implementation NSArray (dataConversion)

/** Convert to NSData, NOT encoding the including objects (only pointers) */
- (NSData*) convertToData {
unsigned n= [self count];
NSMutableData* data = [NSMutableData dataWithLength: sizeof(unsigned)+
sizeof(id) *n];
unsigned* p = [data mutableBytes];
*p++= n;
[self getObjects:(void*)p];
return data;

/** Reciprocal of convertToData */
+ (NSArray*) arrayWithData:(NSData*) data {
unsigned* p = (unsigned*)[data bytes];
unsigned n = *p++;
return [NSArray arrayWithObjects:(id*)p count:n];


Otherwise use NSArchiver (make sure that all objects in the array conform to NSCoding).

Thomas Lachand-Robert
********************** email@hidden
<< Et le chemin est long du projet ` la chose. >> Molihre, Tartuffe.

 >NSMutableArray to NSData (From: email@hidden)

Visit the Apple Store online or at retail locations.

Contact Apple | Terms of Use | Privacy Policy

Copyright © 2011 Apple Inc. All rights reserved.