目标c单例共享实例未被调用

时间:2016-08-26 10:11:03

标签: ios objective-c singleton

我正在尝试在我的应用中实现singlton类。 我的sharedInstance如下

Appmanager.h

#import <Foundation/Foundation.h>

@interface myAppManager : NSObject{

}
+ (id)sharedManager;
-(void)storeData;
@end

Appmanager.m

#import "myAppManager.h"

@implementation myAppManager
+ (id)sharedManager {
  static myAppManager *sharedMyManager = nil;
  static dispatch_once_t onceToken;
  dispatch_once(&onceToken, ^{
     sharedMyManager = [[self alloc] init];
  });
  return sharedMyManager;
}

- (id)init {
  if (self = [super init]) {

  }
  return self;
}
-(void)storeData{
    NSLog(@"store data called");
 }
@end

现在我在didFinishLaunchingWithOptions中从appdelegate调用sharedManager,如下所示

[myAppManager sharedManager];

它没有调用sharedInstance方法,我尝试使用调试点,但它没有调用。 我做错了什么?

[[myAppManager sharedManager] storeData];

这也不是在呼唤。

2 个答案:

答案 0 :(得分:0)

@interface MyAppManager : NSObject

+ (instancetype)sharedManager;

- (void)storeData;

@end

@implementation MyAppManager

+ (instancetype)sharedManager
{
    NSLog(@"%s",__PRETTY_FUNCTION__);

    static MyAppManager *singletonObj = nil;

    static dispatch_once_t onceSecurePredicate;
    dispatch_once(&onceSecurePredicate,^{
                      singletonObj = [[self alloc] init];
                  });

    return singletonObj;
}

- (instancetype)init
{
    NSLog(@"%s",__PRETTY_FUNCTION__);

    self = [super init];

    if (self)
    {
        NSLog(@"initialized!");
    }

    return self;
}

- (void)storeData
{
    NSLog(@"%s",__PRETTY_FUNCTION__);
}

@end

答案 1 :(得分:0)

myAppManager.h

#import <Foundation/Foundation.h>

@interface myAppManager : NSObject
+ (id)sharedManager;
-(void)storeData;
@end

myAppManager.m

#import "myAppManager.h"

@implementation myAppManager

+ (id)sharedManager 
{
  static myAppManager *sharedMyManager = nil;
  static dispatch_once_t onceToken;
  dispatch_once(&onceToken, ^{
    sharedMyManager = [[self alloc] init];
  });
  return sharedMyManager;
}

- (id)init 
{
  if (self = [super init]) {
  }
  return self;
}
-(void)storeData
{
  NSLog(@"store data called");
}
@end

AppDelegate.h

#import <UIKit/UIKit.h>
#import "myAppManager.h"
@interface AppDelegate : UIResponder <UIApplicationDelegate>
{
  myAppManager *appManager;
}
@property (strong, nonatomic) UIWindow *window;
@end

AppDelegate.m

#import "AppDelegate.h"
@interface AppDelegate ()
{
}

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 
{
  // Override point for customization after application launch.
  appManager = [myAppManager sharedManager];
  [appManager storeData];
  return YES;
}

我的控制台输出

2016-08-26 17:07:14.805 SingletonClasswithAppDelegate [2383:77763]存储数据