0

自学 iOS 编程,从这本书开始。我遇到了错误“在‘AppDelegate *’类型的对象上找不到属性‘MainViewController’。

我已经两次和三次检查我是否正确遵循了代码,甚至从头开始重新启动。我搜索了 StackOverflow 并尝试了一些解决方案,但都没有奏效,而且很少能正确匹配我的问题。有什么帮助吗?

AppDelegate.m(错误所在)

#import "AppDelegate.h"
#import "WeatherForecast.h"
#import "MainViewController.h"

@implementation AppDelegate

@synthesize managedObjectContext = _managedObjectContext;
@synthesize managedObjectModel = _managedObjectModel;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    WeatherForecast *forecast = [[WeatherForecast alloc] init];
    self.MainViewController.forecast = forecast;
    // Override point for customization after application launch.
    MainViewController *controller = (MainViewController *)self.window.rootViewController;
    controller.managedObjectContext = self.managedObjectContext;
    return YES;
}

主视图控制器.h

#import "FlipsideViewController.h"
#import "WeatherForecast.h"

#import <CoreData/CoreData.h>

@interface MainViewController : UIViewController <FlipsideViewControllerDelegate>

- (IBAction)showInfo;
- (IBAction)refreshView:(id) sender;
- (void)updateView;

@property (strong, nonatomic) NSManagedObjectContext *managedObjectContext;
@property (strong, nonatomic) WeatherForecast *forecast;

@end
4

1 回答 1

1

问题应该在你的第二行application:didFinishLaunchingWithOptionsself.MainViewController期待您的 AppDelegate 中有一个属性。只需删除此行并在controller.forecast = forecast;之前添加return YES.此时您获得了对 MainViewController 的引用,并且可以安全地设置属性(假设 MainViewController 通过您的 Storyboard 或 XIB 设置为当前的 rootViewController)。

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{    
   WeatherForecast *forecast = [[WeatherForecast alloc] init];
   // Override point for customization after application launch.
   MainViewController *controller = (MainViewController *)self.window.rootViewController;
   controller.managedObjectContext = self.managedObjectContext;
   controller.forecast = forecast;
   return YES;
}
于 2013-06-23T07:53:11.160 回答