【问题标题】:@property in my AppDelegate becomes null when app goes to background in iOS当应用程序在 iOS 中进入后台时,我的 AppDelegate 中的 @property 变为 null
【发布时间】:2017-02-02 11:03:07
【问题描述】:

在我的 AppDelegate 中,我有一个属性。它很强大并且属于自定义类(它是 NSObject 的子类)。当应用程序进入后台时,它变为 NULL。这种行为是不确定的,不能轻易复制(即使使用模拟内存警告选项)。它是随机发生的。

我的理解是,当应用程序进入后台并且如果其他应用程序需要内存时,该应用程序将被终止。但在这种情况下,应用程序并未终止,但特定属性变为空。

我没有在我的任何 ViewController 中实现 didReceiveMemoryWarning。

请帮帮我。

编辑:

这是我的 AppDelegate 外观示例

AppDelegate.h

@interface AppDelegate : UIResponder
@property (nonatomic, strong) UIWindow *window;
@property (nonatomic, strong) UINavigationController *navigationController;
@property (nonatomic, strong) Person *person;//This is the custom class
@end

AppDelegate.m

@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
   // Override point for customization after application launch.
   self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
   self.navigationController = [[UINavigationController alloc] initWithRootViewController:[UIViewController new]];
   self.window.rootViewController = self.navigationController;
   [self.window makeKeyAndVisible];
   return YES;
}
@end

【问题讨论】:

  • 向我们展示您的 AppDelegate 代码。
  • @davidf2281 我已经编辑了我的问题。请检查。

标签: ios objective-c


【解决方案1】:

我建议您覆盖属性的设置器并在其中添加断点。您将看到它何时设置为nil

二传手示例:

- (void)setPerson:(Person *)person {
    _person = person; // breakpoint on this line
}

【讨论】:

    【解决方案2】:

    你没有给我们更多的信息,我不知道你在哪里设置你的 Person 对象。但是您应该确保它没有在某处被删除。例如:当您为该对象分配引用时,引用可能会消失。

    或者,如果您想永久保留该实例,您可以使用 Keychain 或 NSUserDefaults。

    【讨论】:

      【解决方案3】:

      我认为其他一些应用程序不会干扰您的应用程序分配和解除分配。我认为您的应用程序生命周期中存在一些内存泄漏,或者可能是其他一些对象弱指向您的 Person 类,然后当应用程序进入后台状态时没有人指向它时释放您的对象。

      【讨论】:

        【解决方案4】:

        如果应用程序终止,则人员会丢失人员对象,因此请在使用该对象之前将其持久化并获取。对于持久化,您可以使用任何数据库或文件系统,例如 plist 或用户默认值。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-04-19
          • 1970-01-01
          • 2012-07-21
          相关资源
          最近更新 更多