Objective-C-Runtime Bug When Naming a Superclass “Message”

一笑奈何 提交于 2019-12-20 01:45:18

问题


I have the following class hierachy:

@interface Message : NSObject {}
@end

@implementation Message
- (void) dealloc
{
    // I won't be called
    [super dealloc];
}
@end

@interface FooMessage : Message {}
@end

@implementation FooMessage
- (void) dealloc
{
    // should call Message - dealloc
    [super dealloc];
}
@end

And the following unit test:

- (void) test
{
    FooMessage* msg = [[FooMessage alloc] init];
    [msg release];
}

The test will always fail with EXC_BAD_INSTRUCTION. FooMessage calls it's super class destructor in dealloc, but the call never arrives there. Instead, the Objective-C runtime resolves the call to a different location:

The error doesn't occur if the Message base class is renamed to something else, e.g. AbstractMessage. It appears there is another class named Message, whose definition is not publicly available.

Is this a bug? What's really happening here? Am I violating any naming restrictions (even though I think the compiler should warn me about that)?.

It's XCode 3.1. compiling for iPhone OS 3.0.


回答1:


Objectve-C lacks the concept of namespaces. The problem is well known and usually worked-around by using prefix-namespaces (like NSObject or MKMapView). You could name your message class JrMessage to avoid the clash with the (undocumented) class named Message.

The compiler could only warn you if it knew about the other class. In the case of private, undocumented classes, this often is not the case. The best way to handle this is to avoid clashes by using the prefix on every class. This also helps against future clashes, when Apple adds classes to a new release of the OS (which the compiler obviously couldn't warn about).

Edit:

Further investigation shows that the competing class origins from a private Framework named "MIME.framework", at least on the iPhone Simulator:

NSLog(@"Message class: %@", [[NSBundle bundleForClass:NSClassFromString(@"Message")] bundlePath]);

... Message class: /Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator3.1.3.sdk/System/Library/PrivateFrameworks/MIME.framework

You might want to add this information in your bug report.



来源:https://stackoverflow.com/questions/2849804/objective-c-runtime-bug-when-naming-a-superclass-message

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!