【问题标题】:custom [super init] (subclassing)自定义[超级初始化](子类化)
【发布时间】:2014-05-17 13:19:38
【问题描述】:

给定以下类:

MCAchievementCenter:MCModel(子类)

-(id) initWithDelgate:(id<MCAchievementNotifications>)delegate {

    self = [super initWithRessource:@"achievements"];
    if (self)
    {
        self.delegate = delegate;
    }

    return self;
}

MCModel(超类)

-(instancetype)initWithRessource:(NSString *)ressource {

    NSString* ressourcePath = [[NSBundle mainBundle] pathForResource:ressource
                                                              ofType:@"json"];
    NSData* raw = [NSData dataWithContentsOfFile:ressourcePath];
    return [super initWithJSONData:raw];
}

注意-initWithJSONData:rawNSObject 上的一个类别方法,它使用 json 数据填充对象。 (见https://github.com/uacaps/NSObject-ObjectMap

我的问题MCAchievementCenter 的初始化失败,因为它变成了nil

我做错了吗? 任何帮助表示赞赏。

更新:应用进入循环>

【问题讨论】:

  • -initWithJSONData:raw 正在工作。示例:[[MCUser alloc] initWithRessource:@"user"]; 正在返回预期结果。
  • 使用调试器,设置断点并检查变量。 ressourcePath == nil 吗?是原始的 == 零吗? [super initWithJSONData:raw] 返回什么? [super initWithRessource:@"achievements"] 返回什么?等等……
  • 您的屏幕截图仅显示 [[MCAchievementCenter alloc] initWith...] 返回 nil。 - 你已经弄清楚 为什么 它返回 nil。正如我所说:单步执行您的代码并检查变量。将它们与您的预期进行比较。
  • @MartinR 您应该在init 方法中设置self;见文末:blog.wilshipley.com/2005/07/self-stupid-init.html
  • 你能发布你对initWithJSONData:raw:的实现吗?虽然,我必须注意,初始化程序作为在类别中实现的方法 - 不是传统的

标签: ios objective-c oop subclass


【解决方案1】:

检查两件事

  1. MCModel 中的[NSData dataWithContentsOfFile:ressourcePath] 是否为零。

  2. [super initWithJSONData:raw] 在您创建的类别中返回 nil 与否。

可能发生资源在该路径不可用,然后当您调用 super initWithJSONData 时,它也返回 nil,因为 raw 数据为 nil。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-28
    • 1970-01-01
    • 2016-12-30
    相关资源
    最近更新 更多