Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recommend class design in Objective-C

I'm new to Objective-c. For learning purposes I'm trying to build something like a phonebook. So I'll have a class called Person that will have some properties (name, phone, etc).

Right now I'm not preoccupied about persistence. But, I need something to "hold" Person objects. So I thought about create a class called People, but I don't know how to design it, specially the NSMutableArray that will hold the objects.

What I did was:

PERSON.H

@interface Person : NSObject {
   NSString *name;
}
@property(readwrite, copy) NSString *name;
@end

PERSON.M

@implementation Person
@synthesize name;
@end

PEOPLE.H

@interface People : NSObject {
   NSMutableArray *peopleArray;
}
@property(readwrite, retain) NSMutableArray *peopleArray;
- (void)addPerson:(Person *)objPerson;
@end

PEOPLE.M

@implementation People
@synthesize peopleArray;
- (id)init {
   if (![super init]) {
      return nil;
   }
   peopleArray = [[NSMutableArray alloc] retain];
   return self;
}
- (void)addPerson:(Person *)objPerson {
   [peopleArray addObject:objPerson];
}

PHONEBOOK.M

...
Person *pOne = [[Person alloc] init];
pOne.name =@"JaneDoe";

People *people = [[People alloc] init];
[people addPerson:pOne];

When I try to use this code, I receive an error:_method sent to an uninitialized mutable array object.

So, since I'm a newbie, probably the way that I did isn't the best/correct one. So, how do I do this?

like image 879
Bob Rivers Avatar asked Dec 06 '25 07:12

Bob Rivers


1 Answers

Two things wrong with your initialiser for people. It should look more like this:

- (id)init {
   self = [super init];   // always assign the result of [super init] to self.
   if (!self) {
      return nil;
   }
   peopleArray = [[NSMutableArray alloc] init];  // use init not retain.
   return self;
}
like image 139
JeremyP Avatar answered Dec 07 '25 21:12

JeremyP