1

我想知道当您需要为变量分配大量值时,是否可以创建一个 for 循环或类似的东西?

store.item1 = @"asdasd"; 
store.item2 = @"asdasd"; 
store.item3 = @"asdasd"; 
store.item4 = @"asdasd"; 
store.item5 = @"asdasd"; 
store.item6 = @"asdasd"; 
store.item7 = @"asdasd"; 
store.item8 = @"asdasd"; 
store.item9 = @"asdasd"; 

就像是:

for (int i = 0; i < 10; i++)
{
    store.item%i = @"asds"; 
}

提前致谢

4

3 回答 3

4

您可以使用键值编码来做到这一点:

for (int i = 0; i < 10; i++)
{
    [store setValue:@"asdfasd" forKeyPath:[NSString stringWithFormat:@"item%d", i]];
}

但是正如其他答案所建议的那样……如果您确实在商店工作,这可能不是您真正想要的。

于 2012-05-10T12:48:22.157 回答
2

正如JiaYow 所说,使用KVC。

这是一个工作示例:

#import <Foundation/Foundation.h>

@interface Store : NSObject
@property (nonatomic, copy) NSString *item1;
@property (nonatomic, copy) NSString *item2;
@property (nonatomic, copy) NSString *item3;
@property (nonatomic, copy) NSString *item4;
@property (nonatomic, copy) NSString *item5;
@property (nonatomic, copy) NSString *item6;
@end

@implementation Store
@synthesize item1, item2, item3, item4, item5, item6;
@end

int main(int argc, char *argv[]) {
    NSAutoreleasePool *p = [[NSAutoreleasePool alloc] init];

    Store *store = [[Store alloc] init];

    for (int i = 1; i < 7; i++)
    {
        [store setValue:@"asdfasd" forKeyPath:[NSString stringWithFormat:@"item%d", i]];
    }

    [p release];
}

干杯,

约翰内斯

于 2012-05-10T12:51:26.257 回答
0

如果您有一系列变量,请用于NSArray存储它们,而不是单个实例变量。

于 2012-05-10T12:46:22.203 回答