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

时间:2015-11-03 23:39:08

标签: objective-c runtime instances createinstance

到目前为止,我有以下课程:

@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类的新实例。它首先必须存储在NSDictionary中(名称是键并解决值)?

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

1 个答案:

答案 0 :(得分:1)

按照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