Update @ 2012-08-07: As mentioned by Siby, the approach in this article may cause memory leak. Please try to use singleton as shown in the following link.
The Objective-C Singleton
–
Like Java, i would like to add a Static Class such that i could call static variables and static methods in any where.
In Objective-C, you can create a static variable using a static modifier.
For static method which is also known as class method, you can use the + sign instead of the – sign when declaring the method.
I have created a Utility class as follow.
Utility.h
@interface Utility : NSObject
+ (int)getNumber;
+ (void)setNumber:(int)number;
@end
Utility.m
#import "Utility.h"
@implementation Utility
static int number = 1;
+ (int)getNumber {
return number;
}
+ (void)setNumber:(int)newNumber {
number = newNumber;
}
+ (id)alloc {
[NSException raise:@"Cannot be instantiated!" format:@"Static class 'ClassName' cannot be instantiated!"];
return nil;
}
@end
Now i would like to get and set this static variable when loading HelloView. so I need to modify the HelloViewController.m.
HelloController.m
#import "Utility.h"
@implementation HelloController
...
- (void)viewDidLoad {
[super viewDidLoad];
NSLog(@"number = %d", [Utility getNumber]);
[Utility setNumber:3];
NSLog(@"number = %d", [Utility getNumber]);
}
...
@end
Run the application and check the Debugger Console.
2010-04-09 17:27:18.864 HelloWorld[10860:20b] number = 1
2010-04-09 17:27:18.874 HelloWorld[10860:20b] number = 3
Done =)
Update @ 2011-08-25: Add (id)alloc in Utility.m to avoid the class being instantiated. Thanks Liam. =)