Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/objective-c/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 为什么我的sharedInstance返回零?_Ios_Objective C - Fatal编程技术网

Ios 为什么我的sharedInstance返回零?

Ios 为什么我的sharedInstance返回零?,ios,objective-c,Ios,Objective C,我有一个全局属性为“notesArray”的viewController,我想通过singleton从AppDelegate获取它 这是我的appViewController.h #import <UIKit/UIKit.h> @interface AppViewController : UIViewController <UITableViewDelegate, UITableViewDataSource> { NSMutableArray *notesArr

我有一个全局属性为“notesArray”的viewController,我想通过singleton从AppDelegate获取它

这是我的appViewController.h

#import <UIKit/UIKit.h>

@interface AppViewController : UIViewController <UITableViewDelegate, UITableViewDataSource>
{
    NSMutableArray *notesArray;
}


@property (nonatomic, strong) NSMutableArray *notesArray;

+ (AppViewController*)sharedManager;

@end
我的应用程序工作正常,但我需要将其状态保存在NSUserDefaults中,因此在AppDelegate/ApplicationIdentinterBackground中:我创建

- (void)applicationDidEnterBackground:(UIApplication *)application { 
[[NSUserDefaults standardUserDefaults] setObject:[AppViewController sharedManager].notesArray forKey:@"savedNotes"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
但问题是
[AppViewController sharedManager].notesArray=nil
。 我尝试将断点设置为applicationIdentinterBackground:并且来自
[AppViewController sharedManager]=nil的所有数据

很少观察到:

  • notesArray
    不是一个全局属性。它是
    AppViewController
    实例上的属性。现在在#2中,我们看到您打算将其作为一个单例,但由于ObjC并没有一个很好的方法来阻止其他人创建这种类型的第二个对象,您确定您没有创建第二个副本,例如通过cre在XIB中定义这种类型的对象?这可能不是您的问题(请参见#3),但我只想涵盖所有基础

  • 您的
    sharedManager
    方法意味着您将
    AppViewController
    视为一个单体。这对于视图控制器来说是一件不寻常的事情。通常您会有多个视图控制器,而单体将是它们共享的模型的一部分。更好的是,您只需给每个视图控制器一个指向mo的指针有这个数组的del对象,如果你需要第二个列表,一切都会正常工作。还有,为什么它叫“管理器”?它是一个视图控制器

  • 您是否已在调试器中遍历了代码以查看发生了什么?当您尝试在
    ApplicationIdentinterBackground:
    中使用
    NotesRay
    时,
    NotesRay
    有什么值?我在您的代码中没有看到初始化
    NotesRay
    的任何地方。因此,您只有一个指向对象的空指针(即,
    notesArray
    很可能是
    nil
    )。您可能想在singleton类中添加一个
    init
    方法,该方法创建一个
    NSMutableArray
    实例并在
    notesArray
    中记住其地址


  • 尝试初始化
    notesArray
    的代码在哪里?在为其赋值之前,它将是
    nil
    。如果您不确定如何使用调试器查看程序的功能,我不久前写的这篇文章可能会有所帮助:(这是一个更大的C教程的一部分,但调试自己的代码所需了解的内容是相同的)。我目前正在更新它,以覆盖较新Xcode版本中移动的一些UI元素。
    sharedManager
    可能是一个奇怪的单例,但它是一个单例。请注意,该方法是一个类方法。错误(基于OP中的代码和证据)是notesArray可能未初始化。
    - (void)applicationDidEnterBackground:(UIApplication *)application { 
    [[NSUserDefaults standardUserDefaults] setObject:[AppViewController sharedManager].notesArray forKey:@"savedNotes"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    }