1

I wonder if its possible to make a for loop or something similar when you need to assign a lot of values to variables?

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

something like:

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

Thanks in advance

3 Answers 3

4

You can use Key-Value Coding to do that:

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

But as the other answers advised ... this might not be what you really want if you're indeed working on a store.

Sign up to request clarification or add additional context in comments.

2 Comments

you're welcome. But please really bear in mind that usually you don't do things like that. Use this only if you really know what you're doing. If you want to store some items, use arrays or whatever you want. Don't use a property for each item (what happens when one day you end up with, say, 10 items in the store?).
The store was just an example. I have a game that assign all the default values to all the players in the game. If I do this, my code will be about 10x shorter, and much easier :)
2

As JiaYow said, use KVC.

This is a working exapmle:

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

Cheers,

Johannes

Comments

0

If you have a sequence of variables, use NSArray to store them, not individual instance variables.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.