本文介绍了自定义init时'isMemberOfClass'返回'NO'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近偶然发现了一个奇怪的问题:

I recently stumbled over a weird problem:

我正在实现简单的测试用例,并使用NSObject isMemberOfClass方法检查类的相等性.

I was implementing simple Testcases and using the NSObject isMemberOfClass method to check for class equality.

此外,我还实现了一个自定义init:

Additionally I implemented a custom init:

-(id)initWithMessage:(NSString *)message

如果我用正确的类名替换id,则isMemberOfClass将返回'YES'.否则它将失败.

If I replace id with the right class name the isMemberOfClass will return 'YES'. Otherwise it will fail.

有趣的部分是:类Method每次都会返回正确的Class.

The interesting part is: The class Method will return the right Class every time.

这是一个错误吗?还是应该以这种方式工作?

Is this a bug? Or is it supposed to work that way?

谢谢..

好吧,这不能解决问题..这是我的工作.. isMemberOfClass将始终返回NO

Ok this did not solve the problem.. Here is what I do.. isMemberOfClass will always return NO

测试用例:

- (void)test010_broadcastWait
{
    ...
    GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData:xmlData
                                                           options:0 error:&error];
    Brick *newBrick = [self.parser loadBroadcastWaitBrick:doc.rootElement];
    if (![newBrick isMemberOfClass:[BroadcastWaitBrick class]])
        STFail(@"Wrong class-member");
    ....
}

BroadCastWait类别:

BroadCastWait Class:

导入"BroadcastWaitBrick.h"

import "BroadcastWaitBrick.h"

@implementation BroadcastWaitBrick

-(id)initWithMessage:(NSString *)message
{
    self = [super init];
    if (self)
    {
        self.message = message;
    }
    return self;
}

...

loadMethod:

loadMethod:

-(BroadcastWaitBrick*)loadBroadcastWaitBrick:(GDataXMLElement*)gDataXMLElement
{


    NSArray *messages = [gDataXMLElement elementsForName:@"broadcastMessage"];
    GDataXMLElement *message = (GDataXMLElement*)[messages objectAtIndex:0];

    BroadcastWaitBrick* brick = [[BroadcastWaitBrick alloc]initWithMessage:message.stringValue];

    return brick;
}

在您的测试用例中,

推荐答案

isMemberOfClass返回NO,因为您将newBrick var声明为Brick类的成员.

isMemberOfClass in your test case returns NO because you declare newBrick var as a member of class Brick.

在这种情况下,更好的选择是使用isKindOfClass方法或将newBrick声明为id.

Better choice in this case is to use isKindOfClass method or declare newBrick as id.

这篇关于自定义init时'isMemberOfClass'返回'NO'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-23 04:45