Almo
Almo

Reputation: 15861

Why is NSClassFromString returning nil or not in these two cases?

I'm working with CocosBuilder 2.1 and Cocos2d-iPhone 2.0. I've gotten CocosBuilder to compile, and I'm having a weird problem when using their one-text-label example in my project.

Here's the code in question, from CCBReader.m line 823:

Class class = NSClassFromString(className);
if (!class)
{
    NSLog(@"CCBReader: Could not create class of type %@",className);
    return NULL;
}

This fails with the text "Could not create class of type CCLabelTTF". But if I change the code like this:

Class class = NSClassFromString(className);
if (!class)
{
    CCLabelTTF* tempLabel = [[CCLabelTTF alloc] init];
    [tempLabel release];
    NSLog(@"CCBReader: Could not create class of type %@",className);
    return NULL;
}

It works. I don't see anyone else having problems with CocosBuilder in this spot, so what's going on?

The weird thing is that this change can only be affecting it at compiler level, because the added code is inside the error segment, right?

Upvotes: 1

Views: 2751

Answers (2)

Bryan Chen
Bryan Chen

Reputation: 46578

because you did not use CCLabelTTF at all in you project, so the runtime did not load the class for you.

it works after you did the hack because your project now do use the CCLabelTTF class so the runtime will load it.

to solve this problem, add -ObjC to your linker flag, check details in following links

http://developer.apple.com/library/mac/#qa/qa1490/_index.html https://stackoverflow.com/a/2615407/642626

Upvotes: 3

art-divin
art-divin

Reputation: 1645

from the apple documentation:

The class object named by aClassName, or nil if no class by that name is currently loaded. If aClassName is nil, returns nil.

Either you variable "className" is nil, or class was not loaded in runtime before this call. Try to force load this class with this:

[CCLabelTTF class];

anywhere in the code.

For future: try searching your question before creating new one.

Upvotes: 0

Related Questions