开发者

How to declare class array in objective c

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 initWithCapacit开发者_运维知识库y:..

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.


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.


NSMutableArray * users = [NSMutableArray array];
for (int i = 0; i < someNumber; ++i) {
  User * aUser = [[User alloc] initWithStuff:someStuff];
  [users addObject:aUser];
  [aUser release];
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜