Objective-C - iVar Scoped Method Variables?

后端 未结 2 675
鱼传尺愫
鱼传尺愫 2020-12-15 14:50

I was messing around in Objective-C earlier, and I ran into a quite common situation:

I had a class, which was not a singleton, that needed a variable shared between

2条回答
  •  一个人的身影
    2020-12-15 15:35

    I had a class, which was not a singleton, that needed a variable shared between method calls, like static, but each instance needed it's own variable.

    In that case, the variable is part of the object's state, and it's therefore most appropriate to use an instance variable (or a property). This is exactly what ivars are for, whether they're used in a dozen methods or just one.

    I am currently working on an Objective-C++ implementation myself, I was just wondering if anyone else had any thoughts (or existing tools) on how to do this.

    My advice is to not do it at all. If your goal is to avoid clutter, don't go needlessly trying to add a new storage class to the language.

    However, if you're determined to pursue this line, I'd look at using blocks instead of associated objects. Blocks get their own copies of variables that are scoped to the lifetime of the block. For example, you can do this:

    - (void)func
    {
        __block int i = 0;
        void (^foo)() = ^{
            i++;
            NSLog(@"i = %d", i);
        };
    
        foo();
        foo();
        foo();
    }
    

    and the output you get is:

    i = 1
    i = 2
    i = 3
    

    Perhaps you can find a clever way to wrap that up in a macro, but it looks to me like a lot of trouble just to avoid declaring an instance variable.

提交回复
热议问题