I have a variable declared in the header file :
@interface
int _nPerfectSlides;
and
@property (nonatomic, readwrite) int _nPerfectSlides;
and I have a method that I declared in the header :
+ (void) hit;
The method has the following code in it :
+ (void) hit {
NSLog(@"hit");
_nPerfectSlides = 0;
[_game showHit];
}
now for some reason I get the error "Instance variable '_nPerfectSlides' accessed in class method" error and it seems like I cant access any variables inside the method. What am I doing wrong?
Class methods can access class variables and class methods directly. Class methods cannot access instance variables or instance methods directly—they must use an object reference. Also, class methods cannot use the this keyword as there is no instance for this to refer to.
No. 1. Variables declared within a method are local variables. An instance variable is declared inside a class but outside of any method or block.
Instance variables are declared without static keyword. Instance variables can be used only via object reference. Class variables can be used through either class name or object reference.
The public instance variables are visible outside the class, and they can be accessed through a reference to the object to which they belong, by means of the field selection operator ``.
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:
int _nPerfectSlides
in your class file globally.. @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
If you meant to make this an instance method, change that + to -.
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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With