2011-11-04 135 views
16

我有在頭文件聲明的變量:實例變量「變量」類方法錯誤訪問

@interface

int _nPerfectSlides; 

@property (nonatomic, readwrite) int _nPerfectSlides; 

,我有一種方法,其我在標題中聲明:

+ (void) hit; 

的方法中有如下代碼:

+ (void) hit { 
    NSLog(@"hit"); 
    _nPerfectSlides = 0; 
    [_game showHit]; 
} 

現在由於某種原因,我得到的錯誤「實例變量‘_nPerfectSlides’類方法訪問」錯誤,它好像我不能訪問該方法中的任何變量。我究竟做錯了什麼?

回答

20

如果您打算將此作爲實例方法,請將其更改爲 - 。

+0

是的我試過,在發佈之前,它解決了這個問題,但是當我嘗試從另一個類調用方法時,它崩潰了......我該怎麼辦? –

+5

創建該類的實例並調用該實例的實例方法... – Arkku

+6

您似乎沒有理解OOP的核心概念。你是否已經吸收了像這樣的文檔? http://www.otierney.net/objective-c.html – Cyrille

7

顧名思義,實例變量只能在實例方法中使用(使用-聲明)。類方法(用+聲明)不能訪問實例變量,只能訪問self對象。

+0

好吧,所以如何創建一個類方法來訪問它從其他類,而我有權訪問實例變量? –

+3

我不明白你的評論。你可以將'+(void)hit'變成' - (void)hit',或者在全局級聲明'_nPerfectSlides',而不是你的類'@inter'。 – Cyrille

17

1.對於+ (void)hit:只能訪問self對象。

- 第1步:刪除頭文件follwing線

@property (nonatomic, readwrite) int _nPerfectSlides; 

- 步驟2:

  • 添加int _nPerfectSlides在全球範圍類文件..
  • 那表示在@implementation之前申報

例如:在.m File

#import "Controller.h" 
int _nPerfectSlides // Add like this before @implementation 

@implementation Controller 

2.- (void)hit:只能訪問實例方法

3

我知道這是舊的,但它還是來了。嘗試使它成爲一個靜態的。這是我改變代碼以使其增加。

// Hit.h 

#import <Foundation/Foundation.h> 
@interface Hit : NSObject 
+ (void)hit; 
@end 

// Hit.m 

#import "Hit.h" 
@implementation Hit 
static int val = 0; 
+ (void)hit { 
    val += 1; 
    [self showHit]; 
} 
+ (void)showHit { 
    NSLog(@"hit value: %d", val); 
} 
@end 

//main.m 

#import <Foundation/Foundation.h> 
#import "Hit.h" 

int main(int argc, const char * argv[]) { 
    @autoreleasepool { 
     [Hit hit]; 
     [Hit hit]; 
     [Hit hit]; 
    } 
    return 0; 
}