我正在尝试创建一个自定义类别来扩展 UIViewController 的功能,并且在这个类别中我想存储一个指向视图的指针以供重用。我正在使用Ole Begemann描述的关联引用。但是,似乎虽然关联引用本身可以存储和检索 UIView,但将该 UIView 添加到 currentView 会将视图添加为子视图,但后续比较(例如,即使(关联引用)确实已经返回)也[self.view.subviews containsObject:self.storedView]
将始终返回添加到. 此外,即使已将类似代码添加到视图层次结构中,也会始终出现。我猜这是因为我没有完全理解关联引用是如何工作的。NO
self.storedView
self.view
self.storedView.superview
nil
self.storedView
有什么想法可能会出错吗?如果有帮助,我可以提供代码示例。
谢谢!
更新 1:这是一个代码片段,说明我如何self.storedView
通过关联(关联?)引用在类别中创建,然后尝试从视图控制器的view
viaIBAction
方法中添加和删除它。
// UIViewController+TestCategory.m
#import <objc/runtime.h>
static char const * const StoredViewKey = "storedView";
- (void)setStoredView:(UIView *)storedView
{
objc_setAssociatedObject(self, StoredViewKey, storedView, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (UIView *)storedView
{
UIView *storedView = objc_getAssociatedObject(self, StoredViewKey);
if (!storedView)
{
storedView = [[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, self.view.bounds.size.width/2.0, self.view.bounds.size.height/2.0)];
[storedView setBackgroundColor:[UIColor colorWithRed:0.0 green:1.0 blue:0.0 alpha:0.25]];
[storedView setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleBottomMargin)];
}
return storedView;
}
- (IBAction)buttonActionAddStoredView:(id)sender
{
if (![self.view.subviews containsObject:self.storedView]) // always returns YES
{
[self.view addSubview:self.storedView];
}
}
- (IBAction)buttonActionRemoveStoredView:(id)sender
{
if ([self.view.subviews containsObject:self.storedView]) // always returns NO
{
[self.storedView removeFromSuperview];
}
}