【问题标题】:Instance method returns correct array from one view controller but null from others实例方法从一个视图控制器返回正确的数组,但从其他视图控制器返回 null
【发布时间】:2015-08-27 11:11:00
【问题描述】:

这是我的第一篇文章,对于我犯的任何错误,我深表歉意,但这已经让我沮丧了好几个小时,我找不到解决方案。

我有一个使用 UITabBarViewController 的应用程序,它有 3 个选项卡:FirstViewController、SecondViewController 和 ThirdViewController。

我有一个 NSObject 类(管理器),我从视图控制器中伸出手来从日历中提取信息。当我使用 FirstViewController 时,它工作得很好,但是,当我去使用其他视图控制器时,它只返回“null”,但我知道实例方法被调用,因为我在实例方法中放置了一个 NSLog,它返回一个值,但是这个值并没有被传递到视图控制器二和三。

我使用的代码如下。

AppDelegate.m

    #import <UIKit/UIKit.h>
    #import "EventManager.h"

    @interface AppDelegate : UIResponder <UIApplicationDelegate>{

    }

    @property (strong, nonatomic) UIWindow *window;
    @property (nonatomic, strong) EventManager *eventManager;

    @end

AppDelegate.m

    - (void)applicationDidBecomeActive:(UIApplication *)application {

        self.eventManager = [[EventManager alloc] init];

    }

EventManager.h

    #import <Foundation/Foundation.h>
    #import <EventKit/EKEventStore.h>

    @interface EventManager : NSObject

    @property (nonatomic, strong) EKEventStore *eventStore;

    -(NSMutableArray *) fetchCalendars;
    @end

EventManager.m

    -(NSMutableArray *) fetchCalendars {

        NSArray *EKCalendars = [self.eventStore         calendarsForEntityType:EKEntityTypeEvent];

        NSMutableArray *mutableCalendars = [[NSMutableArray alloc]         initWithArray:EKCalendars];
        NSLog(@"EKCalendars %@",EKCalendars);

        return mutableCalendars;
    }

FirstViewController.m

    -(void)loadCalendars{


            NSMutableArray *mutableCalendars = [self.appDelegate.eventManager fetchCalendars];

    }

这对于加载日历非常有效。

SecondViewController.m

    -(void)loadCalendars{


            NSMutableArray *mutableCalendars = [self.appDelegate.eventManager fetchCalendars];

    }

这会返回 null,但是 NSLog[ NSLog(@"EKCalendars %@",EKCalendars)] 的输出与为第一个视图控制器运行代码时的输出完全相同。

我可以从修改 SecondViewController.m 中获取日历来读取

    -(void)loadCalendars{


    EventManager *per= [[EventManager alloc]init];
    calendarsArray =   [per fetchCalendars];

    }

但我只是不明白为什么我需要重新初始化事件管理器,因为它是在 applicationDidBecomeActive 中初始化的。

感谢您提供的任何帮助。

【问题讨论】:

    标签: objective-c xcode methods null instance


    【解决方案1】:

    您可以使用[UIApplication sharedApplication].delegate 访问应用程序的 AppDelegate:

    AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    NSMutableArray *mutableCalendars = [appDelegate.eventManager fetchCalendars];
    

    【讨论】:

    • 嗨,非常感谢!这行得通,但我也意识到我忘了添加: self.appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];在视图中确实加载了。这和你的答案都很好。非常感谢您的快速回复。有没有办法将此标记为已回答?
    猜你喜欢
    • 1970-01-01
    • 2014-06-11
    • 2013-01-08
    • 1970-01-01
    • 1970-01-01
    • 2017-02-13
    • 2020-02-18
    • 2015-10-15
    • 2017-05-26
    相关资源
    最近更新 更多