@Synthesize array of class objects?
Having some difficulty with what I thought would be straight forward. I am trying to make an array of class objects but running into different problems. The goal was to create one class that held an array of another class of objects.
Any help appreciated:
// Basic class unit
@interface MobRec : NSObject {
NSString *MName;
int Speed;
}
@end
// Master Class holding an array of units
@interface MobDefs : NSObject {
MobRec *MobInfo;
}
@property(retain) MobRec *MobInfo;
@开发者_运维问答end
@synthesize MobInfo;
1) From reading it seems I should create and NSMutableArray but how do you declare an NSMutableArray of custom class objects? All iterations I try cause errors. Previously I had predefined the size in the class as MobInfo[20]; but that didnt seem to be good for anything.
2) How do you properly @Synthesize an array of class objects?
I think you misunderstand what @synthesize
does. It creates accessor methods to get and set the property (i.e., it would create a getter method to return that NSMutableArray and a setter method to allow you to replace it with another NSMutableArray). To create an NSMutableArray, you would just create one like any other object in that class's initializer.
NSMutableArray doesn't have any type checking as you add (or read) from it, so you can add any objects you want to it.
In this case I'd have something like:
// MobRec Class
@interface MobRec : NSObject {
NSString *mName;
int speed;
}
@property(retain)NSString *name;
@property(assign)int speed;
@end
@implementation MobRec
@synthesize mName, speed;
@end
// MobDefs Class
#import "MobRec.h"
@interface MobDefs : NSObject {
NSMutableArray *mobInfo;
}
@property(retain) NSMutableArray *mobInfo;
@end
@implementation MobDefs
@synthesize mobInfo;
- (id)init {
mobInfo = [[NSMutableArray alloc] init];
MobRec *aNewMobRec = [[MobRec alloc] init];
[mobInfo addObject:aNewMobRec];
[aNewMobRec release];
}
I've included the basics for adding to the array as well so you can see how its used. Oh and don't forget you have to release the MobInfo in the dealloc method.
But mostly look at NSMutableArray
Your MobDefs
class is not necessary, you can use an NSMutableArray
directly. NSArray
can hold objects of any type, and is declared in just the same way as any other object (such as your MName
property).
精彩评论