実行時にインスタンス変数を動的に作成し、これらの変数をカテゴリに追加したいと思います。インスタンス変数の数は、それらを定義するために使用している構成/プロパティファイルに基づいて変更される場合があります。
何か案は??
実行時にインスタンス変数を動的に作成し、これらの変数をカテゴリに追加したいと思います。インスタンス変数の数は、それらを定義するために使用している構成/プロパティファイルに基づいて変更される場合があります。
何か案は??
私は単に a を使用する傾向がありますNSMutableDictionary
(NSMutableDictionary Class Referenceを参照)。したがって、次の ivar があります。
NSMutableDictionary *dictionary;
次に、それを初期化します。
dictionary = [NSMutableDictionary dictionary];
次に、値をコードで動的に保存できます。たとえば、次のようになります。
dictionary[@"name"] = @"Rob";
dictionary[@"age"] = @29;
// etc.
または、ファイルから読み取っていて、キーの名前がどうなるかわからない場合は、プログラムでこれを行うことができます。
NSString *key = ... // your app will read the name of the field from the text file
id value = ... // your app will read the value of the field from the text file
dictionary[key] = value; // this saves that value for that key in the dictionary
古いバージョンの Xcode (4.5 より前) を使用している場合、構文は次のようになります。
[dictionary setObject:value forKey:key];
何をしたいかにもよりますが、質問はあいまいですが、複数のオブジェクトや複数の整数などが必要な場合は、配列が最適です。100個の数字のリストを含むplistがあるとします。あなたはこのようなことをすることができます:
NSArray * array = [NSArray arrayWithContentsOfFile:filePath];
// filePath is the path to the plist file with all of the numbers stored in it as an array
これにより、NSNumberの配列が得られます。必要に応じて、これをintの配列に変換できます。
int intArray [[array count]];
for (int i = 0; i < [array count]; i++) {
intArray[i] = [((NSNumber *)[array objectAtIndex:i]) intValue];
}
特定の位置から整数を取得したい場合、たとえば5番目の整数を確認したい場合は、次のようにします。
int myNewInt = intArray[4];
// intArray[0] is the first position so [4] would be the fifth
データをプルするためにplistを使用することを検討するだけで、plistを解析することで、コード内にカスタムオブジェクトまたは変数の配列を作成するのが非常に簡単になります。