我似乎无法将数据保存到AppDelegate中的自定义实例对象。我的自定义类非常简单,如下所示:
Person.h
...
@interface Person : NSObject {
int _age;
}
- (void) setAge: (int) age;
- (int) age;
@end
Person.m
#import "Person.h"
@implementation Person
- (void) setAge:(int) age {
_age = age;
}
- (int) age {
return _age;
}
@end
然后我在AppDelegate类中创建了一个Person实例:
AppDelegate.h
@class Person;
@interface AccuTaxAppDelegate : NSObject <UIApplicationDelegate> {
...
Person *person;
}
...
@property (nonatomic, retain) Person *person;
@end
AppDelegate.m
...
#import "Person.h"
@implementation AccuTaxAppDelegate
...
@synthesize person;
- (void)applicationDidFinishLaunching:(UIApplication *)application {
// Override point for customization after app launch
[window addSubview:[navigationController view]];
[window makeKeyAndVisible];
}
- (void)applicationWillTerminate:(UIApplication *)application {
// Save data if appropriate
}
#pragma mark -
#pragma mark Memory management
- (void)dealloc {
[navigationController release];
[window release];
[person release];
[super dealloc];
}
@end
最后,在我的ViewController代码中,我抓住AppDelegate上的一个句柄,然后抓住person实例,但是当我尝试保存年龄时它似乎不起作用:
MyViewController
...
- (void)textFieldDidEndEditing:(UITextField *)textField
{
NSString *textAge = [textField text];
int age = [textAge intValue];
NSLog(@"Age from text field::%i", age);
AppDelegate *appDelegate =
(AppDelegate *)[UIApplication sharedApplication].delegate;
Person *myPerson = (Person *)[appDelegate person];
NSLog(@"Age before setting: %i", [myPerson age]);
[myPerson setAge:age];
NSLog(@"Age after setting: %i", [myPerson age]);
[textAge release];
}
...
上述NSLog的输出为:
[Session started at 2010-05-04 18:29:22 +0100.]
2010-05-04 18:29:28.260 AccuTax[16235:207] Age in text field:25
2010-05-04 18:29:28.262 AccuTax[16235:207] Age before setting: 0
2010-05-04 18:29:28.263 AccuTax[16235:207] Age after setting: 0
为什么'年龄'没有被存储的任何想法?我对Obj-C比较陌生,所以如果我错过了一些非常简单的话,请原谅我!
答案 0 :(得分:3)
看起来你从未真正创建过Person的实例 - 在AccuTaxAppDelegate中添加一个包含该行的init方法
person = [[Person alloc] init];
否则人是零;