Instance variable 'variable' accessed in class method error

后端 未结 4 1962
长发绾君心
长发绾君心 2020-12-14 09:03

I have a variable declared in the header file :

@interface

int _nPerfectSlides;

and

@property (nonatomic, readwri         


        
相关标签:
4条回答
  • 2020-12-14 09:27

    1. For + (void)hit:Only have access to the self object.

    --Step 1: Remove follwing line from header file

    @property (nonatomic, readwrite) int _nPerfectSlides;
    

    --Step 2:

    • Add int _nPerfectSlides in your class file globally..
    • That means declare before @implementation

    Eg: In .m File

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

    2. For - (void)hit:Only have access to the instance methods

    0 讨论(0)
  • 2020-12-14 09:27

    I know this is old, but it still comes up. Try making it a static. Here's I'm altering the code a bit to make it increment.

    // 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;
    }
    
    0 讨论(0)
  • 2020-12-14 09:36

    An instance variable is, as its name suggests, only accessible in the instance methods (those declared with -). Class methods (declared with +) have no access to instance variable, no more than they have access to the self object.

    0 讨论(0)
  • 2020-12-14 09:44

    If you meant to make this an instance method, change that + to -.

    0 讨论(0)
提交回复
热议问题