Recommend class design in Objective-C

I am new to Objective-c. For educational purposes, I'm trying to create something like a phone book. So I will have a class called Person, which will have some properties (name, phone, etc.).

Now I am not concerned about perseverance. But I need something to “hold” Person objects. So I thought about creating a class called People, but I don’t know how to create it, especially NSMutableArray that will hold objects.

What I've done:

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 get the error message: _ method sent to an uninitialized object of a mutable array .

, , , , , /. , ?

+3
3

. :

- (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;
}
+2

init NSMutableArray peopleArray. :

peopleArray = [[NSMutableArray alloc] init];

. , , , :

peopleArray = [[NSMutableArray array] retain];

, . . iPhone Mac, , , , .:)

+2

People.m , ,

peopleArray = [[NSMutableArray alloc] init];

peopleArray = [[NSMutableArray alloc] retain];
+2

Source: https://habr.com/ru/post/1754173/


All Articles