将保留对象分配给弱属性;对象将在分配后释放

时间:2013-02-27 10:42:24

标签: iphone ios

我使用了一些源代码:

 KGModalContainerView *containerView = 
     self.containerView = 
         [[KGModalContainerView alloc] initWithFrame:containerViewRect];

它给了我:Assigning retained object to weak property; object will be released after assignment

修改

@interface KGModal()
  @property (strong, nonatomic) UIWindow *window;
  @property (weak, nonatomic) KGModalViewController *viewController;
  @property (weak, nonatomic) KGModalContainerView *containerView;
  @property (weak, nonatomic) UIView *contentView;
@end

KGModalContainerView *containerView = 
    self.containerView = 
        [[KGModalContainerView alloc] initWithFrame:containerViewRect];
containerView.modalBackgroundColor = self.modalBackgroundColor;
containerView.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin |
                                 UIViewAutoresizingFlexibleRightMargin |
                                 UIViewAutoresizingFlexibleTopMargin |
                                 UIViewAutoresizingFlexibleBottomMargin;
containerView.layer.rasterizationScale = [[UIScreen mainScreen] scale];
contentView.frame = (CGRect){padding, padding, contentView.bounds.size};
[containerView addSubview:contentView];
[viewController.view addSubview:containerView];

2 个答案:

答案 0 :(得分:29)

我认为您的containerView属性是使用weak属性声明的。如果您希望某个属性具有weak属性,则应该已经保留了该属性。这是一个例子:

@property (nonatomic, weak) KGModalContainerView *containerView;
...
-(void)viewDidLoad {
    [super viewDidLoad];
    KGModalContainerView *myContainerView = [[KGModalContainerView alloc] initWithFrame:containerViewRect]; // This is a strong reference to that view
    [self.view addSubview:myContainerView]; //Here self.view retains myContainerView
    self.containerView = myContainerView; // Now self.containerView has weak reference to that view, but if your self.view removes this view, self.containerView will automatically go to nil.

 // In the end ARC will release myContainerView, but it's retained by self.view and weak referenced by self.containerView
}

答案 1 :(得分:3)

我在目标C中作为初学者2美分:

提供警告的行的右侧,

[[KGModalContainerView alloc] initWithFrame:containerViewRect]

在堆中创建一个对象,此时此对象不会被任何指针引用。然后将此对象分配给self.containerView。由于self.myContainerView较弱,因此赋值不会增加右侧创建的对象的引用计数。因此,当赋值完成时,对象的引用计数仍为0,因此ARC立即释放该对象。