开发者

type casting self

What does the following casting of self do "ClassA*"? Does this type caste allow you to access ClassA? ClassA.h:

@interface ClassA: NSObject {
    NSUInteger _someNumber;
    ClassB *_classB;
}
@property (nonatomic,retain) ClassB *classB;
@property (nonato开发者_运维技巧mic,assign) NSUInteger someNumber;

ClassB Method:

-(void) classBMethod {
    [(ClassA*)self setSomeNumber:5];
}


As others have mentioned, if you are dealing with a subclass you should be fine but by the looks of your code I am guessing you would probably be better off with a protocol implementation see http://developer.apple.com/library/ios/#referencelibrary/GettingStarted/Learning_Objective-C_A_Primer/_index.html for an overview.

If that isn't a good fit then you may want to look at calling respondsToSelector first to see if the call will work. http://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Protocols/NSObject_Protocol/Reference/NSObject.html#//apple_ref/occ/intfm/NSObject/respondsToSelector:

But overall, you shouldn't be casting self to another class....


A cast tells the compiler that the variable represents a certain type, even though it is not declared as such. It will get rid of compiler warnings, but it does not affect the compiled output. In this case, it is declaring that the instance of ClassB is actually an instance of ClassA so that it can call setSomeNumber:, but this will only work if the object actually implements that method. If the object is not a member of ClassA or a subclass, and its class doesn't implement the method, your program will crash at runtime.


Is ClassB a subclass of ClassA? If it is, no cast should be necessary.

You can cast any pointer to any class you want to disable a warning that it may not respond to the selector, but if it doesn't respond to the selector at runtime, your app will crash when it tries to call that method and the class does not respond.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜