代码之家  ›  专栏  ›  技术社区  ›  jantimon

如何在objectiveC中将非静态变量从接口移动到实现?

  •  1
  • jantimon  · 技术社区  · 17 年前

    接口文件(myView.h):

    @interface myView: UIView {
    
    NSTimer * myTimer;
    
    }
    
    @end
    

    实现文件(myView.h)

    @implementation myView
    
    @end
    

    接口文件(myView.h):

    @interface myView: UIView {
    
    }
    
    @end
    

    实现文件(myView.h)

    NSTimer * myTimer;
    
    @implementation myView
    
    @end
    

    3 回复  |  直到 16 年前
        1
  •  2
  •   Philippe Leybaert    17 年前

    您不能在实现文件中定义实例变量。

    一个可能的解决方案是有一个包含私有变量的私有结构,并有一个公开声明的私有变量指向这个私有结构:

    @interface MyView {
       void *privateData;
    }
    

    实施文件:

    typedef struct {
       NSTimer *myTimer;
    }  PrivateData;
    
    
    @implementation MyView()
    
    @property (readonly) PrivateData *privateData;
    
    @end
    
    
    @implementation MyView
    
    - (id) init {
       if (self = [super init]) {
           privateData = malloc(sizeof(PrivateData));
    
           self.privateData->myTimer = nil; // or something else
       } 
    
       return self;
    }
    
    -(PrivateData *) privateData {
        return (PrivateData *) self->privateData;
    }
    
    - (void) myMethod {
       NSTimer *timer = self.privateData->myTimer;
    }
    
    - (void) dealloc {
        // release stuff inside PrivateData
        free(privateData);
        [super dealloc];
    }
    
    @end
    

    它不漂亮,但它有效。也许有更好的解决方案。

        2
  •  1
  •   bbum    17 年前

    只是一张便条;为了安全而试图隐藏iVar是愚蠢的。不用麻烦了。

    然而,有几个解决方案:

    Foo.h:

    @interface Foo:NSObject
    @property(readwrite, copy) NSString *publiclyReadwriteNoiVar;
    @property(readonly, copy) NSString *publiclyReadonlyPrivatelyReadwriteNoiVar;
    @end
    

    @interface Foo()
    @property(readwrite, copy) NSString *privateProperty;
    @end
    
    @implementation Foo
    @synthesize publiclyReadwriteNoiVar, publiclyReadonlyPrivatelyReadwriteNoiVar, privateProperty;
    @end
    

    Foo.h:

    @interface Foo:NSObject
    @end
    

    @interface RealFoo:Foo
    {
        .... ivars here ....
    }
    @end
    @implementation RealFoo
    @end
    
    @implementation Foo
    + (Foo *) convenienceMethodThatCreatesFoo
    {
       .... realFoo = [[RealFoo alloc] init]; ....
       return realFoo;
    }
    @end
    
        3
  •  1
  •   pzearfoss    17 年前

    根据封装的目标,还有@private指令:

    Access Modifiers