.h file
#import <Foundation/Foundation.h>
@interface globalFunction : NSObject{
int nbr;
}
@property (nonatomic) NSInteger myInt;
+(void)eventCount:(NSString*) eventName;
@end
.m file
@synthesize myInt;
+(void)eventCount:(NSString *)eventName{
myInt ++;
NSLog(@"Event name %@ and the count %d",eventName, myInt);
}
but this gives me error of Instance variable myInt accessed in class method.
As i searched google, it turned out the problem fixes when i change my global method sign (+) to instance function (-)
but i need a global method where i can use in any of viewController that help me get the count of how many times a specific thing happened during the session.
How can i proceed on this matter?
Use singelton Class to for global counter:
like:
Interface: (in .h)
@interface globalFunction : NSObject
{
int nbr;
}
@property (nonatomic, assign) NSInteger myInt;
+ (instancetype)sharedInstance;
- (void)eventCount:(NSString*) eventName;
@end
Implementation: (in .m)
@implementation globalFunction
#pragma mark - Singleton Class instance
/*
* Singelton instance of globalFunction
*/
+ (instancetype)sharedInstance {
static globalFunction *_instance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_instance = [[globalFunction alloc] init];
});
return _instance;
}
- (void)eventCount:(NSString *)eventName{
_myInt ++;
NSLog(@"Event name %@ and the count %d",eventName, _myInt);
}
@end
and can access using:
[[globalFunction sharedInstance] eventCount:@"Ev"];