开发者

Objective C class reference as property

This should be easy as hell, but I can't figure out the syntax on my own.

Couldn't really formulate the question correctly so I couldn't Google the answer. (you can get why with keywords like objective c, property, class)

Anyhow. In one of my classes I want to save a property which references another class, NOT an instance of another class. Which you easily can accomplish with this cod开发者_运维百科e: @property (nonatomic, assign) Class anotherClass;

Although, I don't want to use the generic Class. I want to use my own classes, but I can't figure how, guess I'd like to do something like @property (nonatomic, assign) @class(MyOwnClass) myClass;


Objective-C does not allow for stack based objects. I don't think you'll be able to do this. You'll have to store a pointer to an instance of a class. class is a method of NSObject, and returns a Class object, which is an instance of meta-class. This is why it works with just class, because you're saving the instance of the meta class object.


You can accomplish this using protocols. Declare your Class property to be a Class object conforming to your new protocol (it need't even have methods), e.g.

@protocol MyProtocol
@end

@property (nonatomic, assign) Class<MyProtocol> anotherClass;

Now simply declare conformance to MyProtocol in all base classes you wish to accept for anotherClass.


You can use a custom setter which raises an NSInvalidArgumentException exception if the value isn't the class you are looking for. You need to use Class.

Due to the fact that every object or class argument is id in Objective-C you can't raise a compile error, just document your code well.


Objective-C doesn't have anything like templates or covariant/contravariant return types. There's no way to say "I want to return a Class object which represents a class which is a subclass of MyOwnClass." You have to use the generic Class pointer.


Maybe I am confused, but couldn't you do this?

Temp.h

@interface Temp : NSObject
    NSString *myString;
@end
@property(nonatomic,assign) NSString *myString;

Temp.m

#import "Temp.h"
@synthesize myString;

MyNewClass.h

#import "Temp.h"
@interface MyNewClass : NSObject
{
}
-(NSString) returnTemp;
@end

MyNewClass.m

#import "MyNewClass.h"
- (NSString) returnTemp
{
    Temp *myTemp = [[Temp alloc] init];
    [myTemp setMyString:@"hello"];
    return myTemp;
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜