我有这段代码(效果很好):
[customServicesArray addObject: userPreferences.aCustomServices1];
[customServicesArray addObject: userPreferences.aCustomServices2];
[customServicesArray addObject: userPreferences.aCustomServices3];
[customServicesArray addObject: userPreferences.aCustomServices4];
[customServicesArray addObject: userPreferences.aCustomServices5];
[customServicesArray addObject: userPreferences.aCustomServices6];
[customServicesArray addObject: userPreferences.aCustomServices7];
[customServicesArray addObject: userPreferences.aCustomServices8];
[customServicesArray addObject: userPreferences.aCustomServices9];
[customServicesArray addObject: userPreferences.aCustomServices10];
[customServicesArray addObject: userPreferences.aCustomServices11];
[customServicesArray addObject: userPreferences.aCustomServices12];
[customServicesArray addObject: userPreferences.aCustomServices13];
[customServicesArray addObject: userPreferences.aCustomServices14];
[customServicesArray addObject: userPreferences.aCustomServices15];
[customServicesArray addObject: userPreferences.aCustomServices16];
[customServicesArray addObject: userPreferences.aCustomServices17];
[customServicesArray addObject: userPreferences.aCustomServices18];
[customServicesArray addObject: userPreferences.aCustomServices19];
[customServicesArray addObject: userPreferences.aCustomServices20];
[customServicesArray addObject: userPreferences.aCustomServices21];
[customServicesArray addObject: userPreferences.aCustomServices22];
[customServicesArray addObject: userPreferences.aCustomServices23];
[customServicesArray addObject: userPreferences.aCustomServices24];
unsortedCustomArray = customServicesArray;
我正试图简化"使用此代码:
unsortedCustomArray = [NSMutableArray new]; // initialize the array
for (NSUInteger i = 0; i < 24; i++) {
NSString *key = [NSString stringWithFormat:@"userPreferences.aCustomServices%u",i+1];
}
我想要&#34;内容&#34;数组中的userPreferences.aCustomServices n ,但我在数组中得到的是:
userPreferences.aCustomServices1,
userPreferences.aCustomServices2,
userPreferences.aCustomServices3,
userPreferences.aCustomServices4,
userPreferences.aCustomServices5,
userPreferences.aCustomServices6,
userPreferences.aCustomServices7,
userPreferences.aCustomServices8,
userPreferences.aCustomServices9,
... and so on...
如何更改代码以便添加userPreferences.aCustomServices对象的内容?
答案 0 :(得分:2)
您可以使用KVC:
[customServicesArray addObject:[userPreferences valueForKey:key]];
但您需要将密钥生成更改为:
NSString *key = [NSString stringWithFormat:@"aCustomServices%u",i+1];