在运行时创build实例variables

我想在运行时dynamic地创build实例variables,我想将这些variables添加到一个类别。 实例variables的数量可能会根据我用于定义它们的configuration/属性文件而改变。

有任何想法吗??

我会倾向于只使用NSMutableDictionary (请参阅NSMutableDictionary类参考 )。 因此,你会有一个伊娃:

 NSMutableDictionary *dictionary; 

你会初始化它:

 dictionary = [NSMutableDictionary dictionary]; 

然后可以在代码中dynamic地保存值,例如:

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

使用关联引用 – 这是棘手的,但这是专门为您的用例发明的机制。

下面是上述链接的一个例子:首先,定义一个引用,并使用objc_setAssociatedObject将其添加到对象; 那么你可以通过调用objc_getAssociatedObject来取回数值。

 static char overviewKey; NSArray *array = [[NSArray alloc] initWithObjects:@ "One", @"Two", @"Three", nil]; NSString *overview = [[NSString alloc] initWithFormat:@"%@", @"First three numbers"]; objc_setAssociatedObject ( array, &overviewKey, overview, OBJC_ASSOCIATION_RETAIN ); [overview release]; NSString *associatedObject = (NSString *) objc_getAssociatedObject (array, &overviewKey); NSLog(@"associatedObject: %@", associatedObject); objc_setAssociatedObject ( array, &overviewKey, nil, OBJC_ASSOCIATION_ASSIGN ); [array release]; 

取决于你想要做什么,问题是模糊的,但如果你想有几个对象或几个整数等,arrays是要走的路。 假设你有一个列表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 

这将给你一个NSNumbers数组,如果你想这样的话,你可以把它转换成一个整数的数组;

 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拉取数据,通过parsingplist就可以很容易地在代码中创build自定义对象或variables的数组。