在objective-c中动态地为变量赋值

时间:2012-05-10 12:41:16

标签: objective-c

我想知道当你需要为变量分配很多值时,是否可以制作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"; 
}

提前致谢

3 个答案:

答案 0 :(得分:4)

您可以使用键值编码来执行此操作:

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

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

答案 1 :(得分:2)

贾义说,使用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];
}

干杯,

约翰

答案 2 :(得分:0)

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