xcode Objective C从nsdictionary添加对象项

时间:2016-04-16 09:05:59

标签: ios objective-c

我有一个像这样的Object类

@interface Recipe : NSObject
@property (nonatomic, strong) NSString *name; // name of recipe
@property (nonatomic, strong) NSString *prepTime; // preparation time
@end

Normaly,我通过这种方式添加新对象。

Recipe *myClass = [Recipe new];
myClass.name = @"This is name";
myClass.prepTime = @"This is time";

Recipe *myClass1 = [Recipe new];
myClass1.name = @"This is name1";
myClass1.prepTime = @"This is time1";

Recipe *myClass2 = [Recipe new];
myClass2.name = @"This is name2";
myClass2.prepTime = @"This is time2";

现在,我有一个来自数组的字典,我想将字典中的所有值都添加到for循环中的对象中。

NSMutableArray *recipes;
NSArray *somoData = [self downloadSoMo];
for (NSDictionary *dict in someData)
{
    Recipe *myClass = [Recipe new];
    myClass.name = [dict objectForKey:@"DreamName"];
    myClass.prepTime = [dict objectForKey:@"Number"];
    [recipes addObject:myClass];
}

上面的代码无法正常工作,我不知道为什么,请帮我解决一下

2 个答案:

答案 0 :(得分:1)

您需要分配食谱 例如   NSMutableArray * recipes = [[NSMutableArray alloc] init];

NSMutableArray *recipes = [[NSMutableArray alloc] init];
NSArray *somoData = [self downloadSoMo];
for (NSDictionary *dict in someData)
{
    Recipe *myClass = [Recipe new];
    myClass.name = [dict objectForKey:@"DreamName"];
    myClass.prepTime = [dict objectForKey:@"Number"];
    [recipes addObject:myClass];
}

答案 1 :(得分:1)

我建议你在Recipe类中创建一个方法来创建它的实例。

像这样,

Recipe.h

- (instancetype) initRecipeWithDictionary:(NSDictionary *)dicRecipe;

Recipe.m

- (instancetype) initRecipeWithDictionary:(NSDictionary *)dicRecipe {
    self = [super init];
    if(self) {
       self.name = [dicRecipe objectForKey:@"DreamName"];
       self.prepTime = [dicRecipe objectForKey:@"Number"];
    }
    return self;
}

现在您可以像这样使用它:

NSMutableArray *recipes = [[NSMutableArray alloc] init];
NSArray *somoData = [self downloadSoMo];
for (NSDictionary *dict in someData)
{
    Recipe *myClass = [[Recipe alloc] initRecipeWithDictionary:dict];
    [recipes addObject:myClass];
}

通过这种方式,您的初始化逻辑将被编写在一个地方,如果您想要更改某些内容,通过更改单个文件Recipe将很容易处理它。