objective-c - Objective C arc——保留对类的引用

标签 objective-c ios automatic-ref-counting

我想要一个Class类型的ivar,传进去之后指针一直在身边。但是不管我怎么做,arc都不让我这么做。例如,如果我声明

@property (nonatomic, strong) Class myClass;

编译器决定 myClass 应该是 unsafe_unretained。如果我尝试这样做:

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

发生的情况是,即使类在调用代码中不是 nil,它在 init 方法中也是 nil。

除了关闭电弧,有什么办法可以解决这个问题吗?

编辑:这个问题是错误的。它确实有效。查看已接受的答案。

最佳答案

与针对 10.7 和 5.1 的 Xcode 4.3.2 一起工作:

@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;
}

你是领先还是落后于 4.3.2?

关于objective-c - Objective C arc——保留对类的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10326440/

相关文章:

ios - Facebook App 邀请通知在 ios 中不起作用

objective-c - Objective-C - 如何实现自定义回调方法但强制执行特定参数?

ios - 如何将 xib 文件加载为自定义类?

objective-c - 使用 ARC 时是否在 dealloc 中将属性设置为 nil?

ios - 如何为特定文件关闭 ARC

ios - 如何每 x 秒刷新 UITableView 的一个随机 UITableViewCell x 次。 Objective-C

ios - 如何在没有 UINotifications IOS 的情况下获取键盘大小

iphone - 发生 ARC 时发出警告?

从 Storyboard重新加载 View 时,以编程方式添加的 iOS subview 将丢失

objective-c - 通过 UIAlerView+AFNetworking 在 UIAlertView 中显示错误消息