xcode目标C添加nsdictionary中的对象项



我有一个类似的Object类

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

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

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

上面的代码不起作用,我不知道为什么,请帮助我修复

您需要分配配方例如。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];
}

我建议您在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中进行更改来轻松处理。

最新更新