2009-09-24 41 views
1

我想寫一個可可觸摸靜態庫。 爲了保持簡單,我不希望在我的界面文件中使用私有變量。 代碼現在看起來是這樣的:如何在ObjectiveC中將非靜態變量從接口移動到實現?

接口文件(myView.h):

@interface myView: UIView { 

NSTimer * myTimer; 

} 

@end 

實現文件(myView.h)

@implementation myView 

@end 

這的NSTimer指針僅僅是一個私有變量所以我試過這個: (不工作)

接口文件(myView.h):

@interface myView: UIView { 

} 

@end 

實現文件(myView.h)

NSTimer * myTimer; 

@implementation myView 

@end 

似乎但是工作原來計時器現在是一個靜態變量。

我做錯了什麼或有沒有解決辦法?

回答

2

您不能在實現文件中定義實例變量。

一個可能的解決方案是讓私人結構包含私有變量,並有一個公開宣稱私有變量指向這個私人結構:

@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 

這不是漂亮,但它的工作原理。也許有更好的解決方案。

+0

這實在是太醜(+1)反正 – jantimon

+0

這應該被更新。您現在可以在您的實現(.m)文件中定義實例變量。 – mahboudz

+0

更新後的解決方案: '@implementation ClassName {//實例變量聲明。 }' http://stackoverflow.com/questions/10407848/is-this-a-new-way-to-define-private-instance-variables-in-objective-c – smileham

1

只是一個說明;爲了安全而試圖隱藏iVar是愚蠢的。不要打擾。

爲了簡單起見,雖然它有價值。

然而,一對夫婦的解決方案:

(1)如果針對iPhone OS或64位可可,你可以@synthesize伊娃:

了foo.h:

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

富.M:

@interface Foo() 
@property(readwrite, copy) NSString *privateProperty; 
@end 

@implementation Foo 
@synthesize publiclyReadwriteNoiVar, publiclyReadonlyPrivatelyReadwriteNoiVar, privateProperty; 
@end 

(2)使用專用子有點像類集羣:

了foo.h:

@interface Foo:NSObject 
@end 

富。L:

@interface RealFoo:Foo 
{ 
    .... ivars here .... 
} 
@end 
@implementation RealFoo 
@end 

@implementation Foo 
+ (Foo *) convenienceMethodThatCreatesFoo 
{ 
    .... realFoo = [[RealFoo alloc] init]; .... 
    return realFoo; 
} 
@end 
相關問題