Objective C arc - saving a reference to a class

I want to have an ivar of type Class and keep the pointer around after passing it. But no matter what I do, arc will not let me do this. For example, if I declare

@property (nonatomic, strong) Class myClass;

the compiler decides that myClass should be unsafe. And if I try this:

-(id) initWithClass: (Class) passedInClass {
   if ((self = [super init])) {
     self.myClass = passedInClass;
   }
   return self;
}

what happens is that even if the class is not zero in the calling code, it is zero in the init method.

Finishing off the arc, is there a way around this?

EDIT: This question is simply incorrect. He works. See Accepted Answer.

+3
source share
1 answer

Works as advertised with Xcode 4.3.2 10.7 and 5.1 targeting:

@interface MOYNObject : NSObject
@property (nonatomic, strong, readwrite) Class myClass;
@end

@implementation MOYNObject
@synthesize myClass;

- (id)initWithClass:(id)pClass
{
    self = [super init];
    if (self != nil)
        self.myClass = pClass;
    assert(self.myClass);
    CFShow((__bridge const void*)self.myClass);
    return self;
}

@end

int main(int argc, const char* argv[]) {
    @autoreleasepool {
        MOYNObject * o = [[MOYNObject alloc] initWithClass:[NSString class]];
        // ...
    }
    return 0;
}

Are you ahead or behind 4.3.2?

+4
source

All Articles