2016-04-16 13 views
-2

から対象項目を追加し、私はこの方法で新しいオブジェクトを追加します。XcodeのObjective Cの私はNormalyこの</p> <pre><code>@interface Recipe : NSObject @property (nonatomic, strong) NSString *name; // name of recipe @property (nonatomic, strong) NSString *prepTime; // preparation time @end </code></pre> <p>のようなオブジェクトのクラスを持っているNSDictionaryの

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

上記のコードは、なぜ、あなたはレシピ 例えばを割り当てる必要が

+0

なぜ準備時間を文字列として保存していますか?数分または数秒の整数を表すIntとしては良いとは思いませんか? – Paulw11

+0

@ Paulw11これはちょうどサンプルコードです、 'prepTime'私は同様に説明として使用します。 – vietnguyen09

+0

「上記のコードは機能していません」とはどういう意味ですか?何がうまくいかないの?どのような症状が見られますか? (NSMutableArrayオブジェクトを割り当てるためには、レシピ配列の宣言を変更する必要があります: 'NSMutableArray * recipes = [NSMutableArray new]'は、あなたのレシピ配列に何も追加されていないということです。 –

答えて

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

Recipeクラスのメソッドを作成してそのインスタンスを作成することをお勧めします。このよう

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

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

Recipe.mRecipe.hであなたはこのようにそれを使用することができます。これにより

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

このようにして、初期化ロジックは1か所に書き込まれます。何かを変更したい場合は、単一のファイルRecipeを変更することで簡単に処理できます。

関連する問題

 関連する問題