Using a string value to define an instance of a class

I have a switch statement similar to this:

    switch (number)
    {
        case 1:
            if (imageView1.hidden == NO)
            {
                imageView1.hidden = YES;                    

            } else 
            {
                imageView1.hidden = NO;
            }


            break;
        case 2:
            if (imageView2.hidden == NO)
            {
                imageView2.hidden = YES;


            } else 
            {
                imageView2.hidden = NO;
                            }

            break;

And so on and so forth.

My question is: how can I use a string with the value "imageView1" and use this to access an instance of my imageView class instead of having a separate case for each imageView instance? I know that it will be like creating NSPath from a string or something like that, but I'm just not sure where to look or what it will be called.

Thanks in advance for your help!

+3
source share
2 answers

, , . , , . Objective-C, .

, Key Value, -valueWithKey:.

NSString *nameOfView = @"imageView1";
[[self valueForKey:nameOfView] setHidden:YES];

-imageView1, ivar imageView1 , , ivar _imageView1. Cocoa, . , , , , . " ".

- JimG, NSArray , , , . , , KVC .

+5

NSArray ?

NSArray *views = [NSArray arrayWithObjects: imageView1, imageView2, nil];
NSImageView *iview = [views objectAtIndex: number];

, - :

iview.hidden = ! iview.hidden;

[: , oops]

+4

Source: https://habr.com/ru/post/1709036/


All Articles