Reputation: 54248
I have a objective-C static library ( iOS SDK 6 ):
Implementation file ( .m )
#import "MyClass.h"
@implementation MyClass
static id _instance;
static NSString *version;
- (id)init {
if(_instance == nil) {
_instance = [super init];
version = @"1.0";
}
return _instance;
}
- (NSString *)getVersion {
return version;
}
+ (MyClass *)sharedInstance {
return _instance;
}
@end
When I access the class in other iPhone App project (imported the library), I cannot get the version string.
#import "ViewController.h"
#import <MyClass/MyClass.h>
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
MyClass *cls = [MyClass sharedInstance];
NSLog(@"Loaded. Version: %@", [cls getVersion]);
}
@end
What did I miss? No error is reported, but version is (null)
Upvotes: 0
Views: 157
Reputation: 21259
There's lot of mistakes ...
init
is not called at all... you seem try to use singleton pattern. So, do this ...
+ (MyClass *)sharedInstance {
static MyClass *instance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
instance = [[[self class] alloc] init];
});
return instance;
}
... and change your init
to ...
- (id)init {
self = [super init];
if ( !self ) {
return nil;
}
_version = @"1.0";
return self;
}
... and call [[MyClass sharedInstance] getVersion]
to get your version.
P.S. Read ObjC guide and don't use get
prefix. Should be just version
.
Upvotes: 3