Search code examples
objective-cruntimeinstancescreateinstance

Create Instances During Runtime in Objective C


I have the following class so far:

@interface BRPerson : NSObject
@property (nonatomic) NSString *name;
@property (nonatomic) NSString *address;

-(instancetype)initWithName:(NSString*)name andAddress:(NSString*)address;

@implementation BRPerson

-(instancetype)initWithName:(NSString*)name andAddress:(NSString*)address{
    self.name = name;
    self.address = address;
    return self;
}
@end

and my main is:

#import <Foundation/Foundation.h>
#import "BRPerson.h"

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        NSString *filepath = [[NSBundle mainBundle] pathForResource:@"Directory"
                                                             ofType:@"txt"];
     }
     return 0;
 }

The Directory.txt file is a plain file I created that is set up as:

name, address
name2, address2
name3, address3

I am trying to write a program that reads names and addresses and creates a new instance of the BRPerson class with the name being the instance name. Would it first have to be stored in NSDictionary (with name being the key and address the value)?

Any help is appreciated. Thank you in advance.


Solution

  • Following Objective-C's pattern for initializers, do the following:

    -(id)initWithName:(NSString*)name andAddress:(NSString*)address{
        self = [super init];
        if (self) {
            _name = name;
            _address = address;
        }
        return self;
    }
    

    You might also consider providing a convenience factory method, like this:

    + (instancetype)personWithName:(NSString*)name andAddress:(NSString*)address {
        return [[self alloc] initWithName:name andAddress:address];
    }
    

    With this, the loop that builds the instances will look like many parts of the SDK:

    NSMutableArray *persons = [@[] mutableCopy];
    while (/* more input */) {
        NSString *name = // next name from input
        NSString *address = // next address from input
    
        BRPerson *person = [BRPerson personWithName:name andAddress:address];
        [persons addObject];
    }
    // here, the array persons will contain several BRPerson instances
    // as specified by the input