tags:

views:

79

answers:

2

I can declare NSMutableArray or NSArray but I want to declare class array. Let say user is a class so I can declare array as:

user* obj[10];

it is valid in Objective c, but I am not sure how I can set array capacity dynamically. Which we usually do with MutableArray as initWithCapacity:..

This is what I am doing with class:

user* objuser;
CustomOutput* output = [[CustomOutput alloc] init];
[objuser cutomSerialize:output];
NSMutableData* data = output.data;

But If I have array as:

NSMutableArray* aryUserObj;

I can't call cutomSerialize method from arryUserObj.

I want to Serialize all the userObj at ones and get a single NSData object.

+2  A: 
NSMutableArray * users = [NSMutableArray array];
for (int i = 0; i < someNumber; ++i) {
  User * aUser = [[User alloc] initWithStuff:someStuff];
  [users addObject:aUser];
  [aUser release];
}
Dave DeLong
I know this... but I don't want to use NSMutableArray need to use only class array. Because I have to serialize this class object and I can assess serialize method only in class not from MutableArray. Ex: obj.serialize(data); This could possible only if I have class obj.
iPhoneDev
@iPhoneDev you can still iterate the objects in the array and serialize them, or you can implement the `<NSCoding>` protocol, then just serialize all of the objects at once by serializing the array.
Dave DeLong
Yes this I want to serialize all object at ones and send it as NSData. Please let me know how we can use `NSCoding` for this..
iPhoneDev
@iPhoneDev read the documentation on Archiving and Serializations and let us know what questions you have: http://developer.apple.com/library/ios/#documentation/cocoa/Conceptual/Archiving/Archiving.html
Dave DeLong
Please find the edited code
iPhoneDev
+4  A: 

The standard approach to serialize an array of objects is for you to define encodeWithCoder: and initWithCoder: in your User object:

@interface User: NSObject {
 ....
}
-(void)encodeWithCoder:(NSCoder*)coder ;
-(id)initWithCoder:(NSCoder*)coder;
@end 

What you currently have in CustomSerialize should be in these methods.

Then, if you want to encode an object, you do

User* user=... ;
NSData* data=[NSKeyedArchiver archivedDataWithRootObject:user];

and decode it:

User* user=[NSKeyedUnarchiver unarchiveObjectWithData:data];

If you have an array of objects,

NSMutableArray* array=... ; // an array of users
NSData* data=[NSKeyedArchiver archivedDataWithRootObject:array];

and

NSArray* array=[NSKeyedUnarchiver unarchiveObjectWithData:data];

Iteration over array is done automatically. Note also that you don't get the mutable array back, it's an immutable array.

Yuji
+1, except that `NSKeyedUnarchiver` does not maintain the mutability of the objects. IOW, if you archive an `NSMutableArray`, you're going to get an `NSArray` back. It's kind of lame, but that's how it goes.
Dave DeLong
You're perfectly right. Corrected.
Yuji