iPhone - 属性,ivars等

时间:2012-02-25 09:55:41

标签: iphone ios objective-c-blocks

this tutorial上,作者有这些声明:

on .h

UIViewController *presentingViewController;
...

@property (retain) UIViewController *presentingViewController;

on .m

@synthesize presentingViewController;

在代码的某个时刻,在一个区块内,他确实:

self.presentingViewController = viewController;

然后

[presentingViewController dismissModalViewControllerAnimated:NO];

我发现这很奇怪。如果是将viewController分配给self.presentingViewController,则不应该调用

    [self.presentingViewController dismissModalViewControllerAnimated:NO];

我已将代码更改为

·H

@property (retain) UIViewController *presentingViewController;

的.m

@synthesize presentingViewController = _presentingViewController;

我所做的是:

self.presentingViewController = viewController;

然后

    [self.presentingViewController dismissModalViewControllerAnimated:NO];

问题是,self.presentingViewController在这一行是零,甚至被声明为retain并且永远不会被释放。

任何线索?

感谢

2 个答案:

答案 0 :(得分:0)

你说得对,应该是:

[self.presentingViewController dismissModalViewControllerAnimated:NO];

然而,恢复此:

@synthesize presentingViewController;

删除类似外观变量的实例修饰:

UIViewController *presentingViewController;

答案 1 :(得分:0)

添加实例变量UIViewController *presentingViewController时是否删除了实例变量UIViewController *_presentingViewController?如果不是,我会在某个时候意外地使用错误的钱给你钱。

单步执行..最初你有一个实例变量

UIViewController *presentingViewController;

从属性语法糖中你可以使用两种访问器方法来设置和获取变量

- (UIViewController *)presentingViewController;
- (void)setPresentingViewController:(UIViewController *)val;

在代码的某个时刻,在一个街区内,他做了:

[self setPresentingViewController: viewController]; // uses setter

然后

[presentingViewController dismissModalViewControllerAnimated:NO]; // uses instance variable

这很好,但你认为它应该是

UIViewController *localPresentingViewController = [self presentingViewController]; // uses getter
[localPresentingViewController dismissModalViewControllerAnimated:NO];

这也很好,但有些不必要。

然后你添加了一个新的实例变量: -

@synthesize presentingViewController = _presentingViewController;

所以现在你有了

UIViewController *presentingViewController;
UIViewController *_presentingViewController;

// These now get / set _presentingViewController
- (UIViewController *)presentingViewController;
- (void)setPresentingViewController:(UIViewController *)val;

但是几乎可以肯定的是,在某些地方你会混淆两个ivars(或者你不知道你有两个ivars)提交了ViewController / _presentingViewController,并且仍然引用了presentViewController ivar,导致你认为你的属性是零。