gpt4 book ai didi

ios - 变量总是按值传递

转载 作者:行者123 更新时间:2023-11-28 21:39:54 25 4
gpt4 key购买 nike

我有 2 个类 AuthManagerAuthView。我想在实现 AuthView 文件 (.m) 中加载 AuthView 的 nib 文件。我在 AuthView 中创建了一个静态方法:

+ (void)loadAuthView:(AuthView *)handle
{
NSBundle * sdkBundle = [NSBundle bundleWithURL:
[[NSBundle mainBundle]
URLForResource:SDK_BUNDLE_NAME withExtension:@"bundle"]];
// handle == nil
handle = [[sdkBundle loadNibNamed:AUTHVIEW_NIB_NAME owner:nil options:nil] firstObject];
// handle != nil
}

AuthManager 中,我有一个属性:

@property (nonatomic, strong) AuthView * _authView;

还有一个方法:

- (void)showAuthViewInView:(UIView *)view
{
if (__authView == nil) {
[AuthView loadAuthView:__authView];
// __authView ( handle ) == nil ??????????????
}

[__authView showInView:view];
}

问题:在 loadAuthView 内部,__authView (handle) 是 != nil。但是 __authViewloadAuthView 之外被释放。

问题:为什么会这样?以及如何保持__authView(handle)不被释放?

而且,如果我在 AuthManager 中加载 nib,它工作正常。

- (void)showAuthViewInView:(UIView *)view
{
if (__authView == nil) {
NSBundle * sdkBundle = [NSBundle bundleWithURL:
[[NSBundle mainBundle]
URLForResource:SDK_BUNDLE_NAME withExtension:@"bundle"]];
__authView = [[sdkBundle loadNibNamed:AUTHVIEW_NIB_NAME owner:nil options:nil] firstObject];
}

[__authView showInView:view];
}

如有任何帮助或建议,我们将不胜感激。

谢谢。

最佳答案

您必须返回句柄,以便 ARC 知道该对象仍被引用。

loadAuthView: 更改为

+ (AuthView *)loadAuthView
{
NSBundle * sdkBundle = [NSBundle bundleWithURL:
[[NSBundle mainBundle]
URLForResource:SDK_BUNDLE_NAME withExtension:@"bundle"]];
// handle == nil
AuthView *handle = [[sdkBundle loadNibNamed:AUTHVIEW_NIB_NAME owner:nil options:nil] firstObject];
// handle != nil
return handle;
}

- (void)showAuthViewInView:(UIView *)view
{
if (__authView == nil) {
__authView = [AuthView loadAuthView];
}

[__authView showInView:view];
}

您对变量总是按值(而不是引用)传递感到困惑。在您的原始代码中,修改 loadAuthView 中的 handle不会修改 __authView 的值,因为 handle__authView 的新副本。修改 __authView 的唯一方法是使用 = 运算符直接为其赋值(现在让我们忽略指向指针的指针)。

这是一个简单的例子:

void add(int b) {
// b is 1
b = b + 1;
// b is 2
} // the value of b is discarded
int a = 1; // a is 1
add(a);
// a is still 1

void add2(int b) {
return b + 1;
}
a = add2(a);
// a is 2 now

另一种修复原始方法的方法(不推荐)是使用双指针 (AuthView **)

+ (void)loadAuthView:(AuthView **)handle
{
NSBundle * sdkBundle = [NSBundle bundleWithURL:
[[NSBundle mainBundle]
URLForResource:SDK_BUNDLE_NAME withExtension:@"bundle"]];
*handle = [[sdkBundle loadNibNamed:AUTHVIEW_NIB_NAME owner:nil options:nil] firstObject];
}

AuthView *authView; // make a local variable to avoid ARC issue
[AuthView loadAuthView:&authView];
__authView = authView;

关于ios - 变量总是按值传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32577445/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com