2013-02-27 111 views
11

后公布我使用的一些源代码:将保留对象分配给弱属性;对象将分配

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]; 
+1

没有足够的信息来回答你的问题。如何定义'self.containerView'?用ARC编译KGModalContainerView吗? – trojanfoe 2013-02-27 10:47:39

+0

我编辑我的问题,我正在使用ARC – pengwang 2013-02-28 01:51:45

+0

你真的必须在一行中有两个任务吗?如果你不这样做会发生什么?为什么你必须将一个本地'containerView' *和*分配给一个属性'self.containerView'?那应该是什么意思? – matt 2013-02-28 02:04:05

回答

28

我想你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

我修改了代码,但也有唠叨 – pengwang 2013-02-28 01:51:09

2

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

给出警告的线的右侧,

[[KGModalContainerView alloc] initWithFrame:containerViewRect] 

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

相关问题