Re: NSMutableArray to NSData
Re: NSMutableArray to NSData
- Subject: Re: NSMutableArray to NSData
- From: Thomas Lachand-Robert <email@hidden>
- Date: Sun, 6 Jan 2002 16:40:17 +0100
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];
}
@end
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.