【问题标题】:when will release or nil variables in ARC?什么时候在 ARC 中释放或 nil 变量?
【发布时间】:2014-04-11 13:13:42
【问题描述】:

我创建了一个类用于在我的应用程序中声明全局变量。

.h 文件

@interface GlobalVariables : NSObject

@property (nonatomic, strong) NSString *strTemp1;
@property (nonatomic, strong) NSArray *arrTemp1;

+ (GlobalVariables *)sharedInstance ;

.m 文件

#import "GlobalVariables.h"

@implementation GlobalVariables

+ (GlobalVariables *)sharedInstance
{
    static GlobalVariables *sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
       sharedInstance = [self new];
        // Do any other initialisation stuff here
        NSLog(@"alloc and intialize");
    });
    return sharedInstance;
}

现在在某个类中,我设置了这个变量的值。

 [[GlobalVariables sharedInstance] setStrTemp1:@"Temp1"];
 [[GlobalVariables sharedInstance] setArrTemp1:[NSArray arrayWithObjects:@"Name",@"Address",@"Contact NO", nil]];

并且在其他类中也得到这个值。

NSLog(@"Get string value : %@", [[GlobalVariables sharedInstance] strTemp1]);
NSLog(@"Get arr value : %@", [[GlobalVariables sharedInstance] arrTemp1]);

现在我的问题是这个变量什么时候是 release 或 nil?

我在我的项目中使用 ARC。

我知道 arc 会自动释放它,但何时以及如何释放?

【问题讨论】:

  • 如果你使用 ARC,你真的不应该关心它何时或如何释放它的内存。
  • 在 iOS 5 之前没有 ARC 男人的概念,你必须释放你创建的所有对象......如果你忘记了任何一个,会有一个警告显示内存泄漏......所以在 iOS 5 之后,ARC(自动引用计数)......你分配你的对象并忘记那些没有任何问题

标签: objective-c memory-management ios7 automatic-ref-counting


【解决方案1】:

这是一个单例类,具有属性的类将一直存在,直到您完成应用程序或应用程序因其他原因终止。

【讨论】:

  • 或者如果你给它分配nil
  • 如果你赋值为 nil,这意味着该对象中没有任何值...但是该对象将保留一个引用...
  • 因此您必须在 ARC 之前释放该对象以删除引用并释放内存
  • 也许如果引用它的所有内容都是weak 变量,arc 会按预期清理它,但我不确定。
猜你喜欢
  • 2012-01-30
  • 1970-01-01
  • 2021-10-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-07
  • 2015-06-25
相关资源
最近更新 更多