我在iPhone上有iOS4项目。
app delegate的实例变量是一个字典,当app启动时,它会从plist加载全局只读数据。
CalculatorAppDelegate.h
#import <UIKit/UIKit.h>
@class MainViewController;
@interface CalculatorAppDelegate : NSObject <UIApplicationDelegate> {
NSDictionary *RGBSpacesDictionary;
}
@property (nonatomic, retain) IBOutlet UIWindow *window;
@property (nonatomic, retain, readonly) NSDictionary *RGBSpacesDictionary;
@property (nonatomic, retain) IBOutlet MainViewController *mainViewController;
@end
CalculatorAppDelegate.m
#import "CalculatorAppDelegate.h"
#import "MainViewController.h"
@implementation CalculatorAppDelegate
@synthesize mainViewController=_mainViewController;
@synthesize RGBSpacesDictionary;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// load plist
NSString* plistPath1 = [[NSBundle mainBundle] pathForResource:@"RGBSpaces" ofType:@"plist"];
RGBSpacesDictionary = [NSDictionary dictionaryWithContentsOfFile:plistPath1];
etc.
}
然后在MainViewController中,我能够在viewDidLoad
中成功读取字典MainViewController.h
@class CalculatorAppDelegate;
@interface MainViewController : UIViewController <FlipsideViewControllerDelegate> {
CalculatorAppDelegate *appDelegate;
}
@property (nonatomic, retain) CalculatorAppDelegate *appDelegate;
etc.
}
MainViewCOntroller.m
#import "CalculatorAppDelegate.h"
@implementation MainViewController
@synthesize appDelegate;
- (void)viewDidLoad
{
[super viewDidLoad];
appDelegate = [[UIApplication sharedApplication] delegate];
RGBSpacesCount = (int) [appDelegate.RGBSpacesDictionary count];
}
在viewDidLoad中一切正常,我可以将我的字典读作appDelegate.REGSpaceDictionary。
问题在于按下按钮时调用MainVievController的另一种方法
- (IBAction) RGBSpaceButtonPressed {
NSLog(@"appDelegate.RGBSpacesDictionary %@", appDelegate.RGBSpacesDictionary);
etc.
}
此时调用字典(例如使用NSLog)会在崩溃时返回。
有人能帮助我吗?谢谢。
答案 0 :(得分:3)
在这一行
RGBSpacesDictionary = [NSDictionary dictionaryWithContentsOfFile:plistPath1];
您正在将autoreleased
物体直接分配到ivar,因此无法保证它会保留多长时间。您应该分配一个非自动释放的对象或通过setter
// Going through the setter
self.RGBSpacesDictionary = [NSDictionary dictionaryWithContentsOfFile:plistPath1];
// OR
// Non assigning a non autoreleased object
RGBSpacesDictionary = [[NSDictionary alloc] initWithContentsOfFile:plistPath1];
要使用设置器,您必须重新声明应用代理property
文件顶部的扩展程序中的.m
@interface CalculatorAppDelegate ()
@property (nonatomic, retain, readwrite) NSDictionary *RGBSpacesDictionary;
@end
...
The rest of your implementation
答案 1 :(得分:1)
尝试在app delegate中保留字典。它必须在某个时候解除分配,因为你得到一个自动释放的,你没有使用该属性来设置它。
// here you must retain the dictionary
[[NSDictionary dictionaryWithContentsOfFile:plistPath1] retain];
当然不要忘记稍后在dealloc中发布它。