在自动释放 ios 项目中保留变量

Posted

技术标签:

【中文标题】在自动释放 ios 项目中保留变量【英文标题】:retain a variable in a autorelease ios project 【发布时间】:2013-02-27 03:52:19 【问题描述】:

我是 ios 编程的初学者,我的项目设置为自动释放,现在我遇到了自动释放功能的问题。我展示了我的代码,希望你能支持我避免这种情况

- (void)initPhotoImage

    photoImage = [[MyPhotoImageView alloc] initWithFrame:CGRectMake(5, 30, 0, 0)];
    photoImage.photoViewController = self;
    [photoView addSubview:photoImage];

    UISwipeGestureRecognizer *gesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(didSwipeLeft:)];
    gesture.direction = UISwipeGestureRecognizerDirectionLeft;
    [photoView addGestureRecognizer:gesture];
    UISwipeGestureRecognizer *gesture1 = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(didSwipeRight:)];
    gesture1.direction = UISwipeGestureRecognizerDirectionRight;
    [photoView addGestureRecognizer:gesture1];



-(void)didSwipeLeft:(UIGestureRecognizer *)gestureRecognizer 

    if(self.nextViewController != NULL)
        [UIView animateWithDuration:1 animations:^
            self.view.frame = CGRectMake(-1*self.view.frame.size.width, 0, self.view.frame.size.width, self.view.frame.size.height);
        ];
        NSLog(@"next");
    else
        NSLog(@"next view is null");
    

这两个函数在同一个类中,我在 init 函数中打印 self.nextViewController,它打印一个地址但在 swip 函数中,我再次打印 self.nextViewController 但它打印空地址,在 .h 文件中我定义它保留

@property (retain, nonatomic) MyPhotoViewController *nextViewController;

【问题讨论】:

在哪里分配 nextViewController?上面的代码中没有定义... 它不是您问题的答案,而只是通知.. 您必须释放 gesturegesture1 我的项目设置为自动发布,所以我不能使用发布方法 【参考方案1】:

改变这个

if(self.nextViewController != NULL)

if(self.nextViewController != nil)

【讨论】:

你确定吗?我认为 Nil(大写 N)用于测试类是否为零。 nil(小写 n)用于测试对象。 其实两者都是一样的。它们都为零,但“NULL”是一个 void *,“nil”是一个 id,“Nil”是一个类指针。 这个变化是什么意思,我认为 nil 和 null 的意思是一样的 如果两者相同且可替换,知道为什么语言有两个吗?他们可以简单地拥有一个。 @Makio,这里有更详细的答案***.com/questions/557582/null-vs-nil-in-objective-c

以上是关于在自动释放 ios 项目中保留变量的主要内容,如果未能解决你的问题,请参考以下文章

自动释放:必须[保留]成员变量?

使用自动释放池和环境变量进行调试

stringByAppendingString 和保留困境

@property(保留)是不是自动释放或释放对象?

在 iOS 7.1 更新中自动释放的变量崩溃,但在 iOS 7.1 之前的操作系统版本中工作正常

在 sdk 5 中替换 release