【问题标题】:Accessing Properties in Static Library in iOS App在 iOS 应用程序中访问静态库中的属性
【发布时间】:2013-05-23 19:05:11
【问题描述】:

我有一个 Objective-C 静态库(iOS SDK 6):

实施文件 (.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

当我访问其他 iPhone App 项目中的类(导入库)时,我无法获取版本字符串。

#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

我错过了什么?没有报错,但是版本是(null)

【问题讨论】:

  • 你能展示一下召唤的实现吗?
  • 对不起,应该是sharedInstance 而不是summon
  • 真的调用了init吗?我不这么认为。
  • 尝试打印id cls,并确认其类类型。我想这就是你错过了什么的地方。

标签: iphone objective-c


【解决方案1】:

有很多错误...

  • init 根本没有被调用

...您似乎尝试使用单例模式。所以,就这样吧……

+ (MyClass *)sharedInstance {
  static MyClass *instance = nil;
  static dispatch_once_t onceToken;
  dispatch_once(&onceToken, ^{
    instance = [[[self class] alloc] init];
  });
  return instance;
}

... 并将您的 init 更改为 ...

- (id)init {
  self = [super init];
  if ( !self ) {
    return nil;
  }

  _version = @"1.0";
  return self;
}

...并致电[[MyClass sharedInstance] getVersion] 获取您的版本。

附:阅读 ObjC 指南,不要使用 get 前缀。应该只是version

【讨论】:

  • 对不起我的新手Obj-C技能。似乎我遵循了错误的教程。现在运作良好。但我不明白为什么需要dispatch_once
  • dispatch_once 只调用一次该块,这意味着您的类 sharedInstance 方法总是返回相同的对象。阅读此示例 - en.wikipedia.org/wiki/Singleton_pattern
猜你喜欢
  • 2018-04-18
  • 2017-08-15
  • 1970-01-01
  • 2015-05-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多