在 Objective C 中在运行时创建实例

Create Instances During Runtime in Objective C

到目前为止,我有以下 class:

@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

我的主要是:

#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;
 }

Directory.txt 文件是我创建的普通文件,设置为:

name, address
name2, address2
name3, address3

我正在尝试编写一个程序来读取姓名和地址并创建一个新的 BRPerson class 实例,名称是实例名称。它是否首先必须存储在 NSDictionary 中(名称是键,地址是值)?

感谢任何帮助。提前谢谢你。

跟随 Objective-C 的 pattern for initializers,执行以下操作:

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

您也可以考虑提供一个方便的工厂方法,如下所示:

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

有了这个,构建实例的循环将看起来像 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