请帮助我:
AppDelegate有一个名为“user”的参数:
@interface AppDelegate : UIResponder <UIApplicationDelegate>
{
User *user;
}
@property (nonatomic, retain) User *user;
我在frist viewController中初始化用户实例:
User *userInfo = [[User alloc] initWithRealName:realName UserId:userId];
并将用户设置为AppDelegate:
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
appDelegate.user = userInfo;
在第二个viewController中,我可以得到use的realName,没有问题:
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
NSString *realName = appDelegate.user.realName;
但是当我推送到另一个viewController时,我想要像刚才那样得到用户的真实名称, 但是有一个错误:EXC_BAD_ACCESS:
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
User *user = appDelegate.user;
NSLog(@"I am in noticeDetailViewController:%@",user.realName);***//ERROR***
我想知道为什么?以及如何解决此错误。
谢谢!
User.h & User.m
@interface User : NSObject
{
NSString *realName;
NSString *userId;
}
@property (nonatomic, retain)NSString *realName;
@property (nonatomic, retain)NSString *userId;
- (id)initWithRealName :(NSString *)realNameArgument UserId :(NSString *)userIdArgument;
@end
@implementation User
@synthesize realName,userId;
- (id)initWithRealName :(NSString *)realNameArgument UserId :(NSString *)userIdArgument
{
self = [super init];
if (self)
{
realName = realNameArgument;
userId = userIdArgument;
}
return self;
}
- (void)dealloc
{
[super dealloc];
[realName release];
[userId release];
}
@end
答案 0 :(得分:0)
AppDelegate
未保留user
,因此在您尝试访问它之前会将其取消分配:
NSLog(@"I am in noticeDetailViewController:%@",user.realName);***//ERROR***
因此,通过创建保留属性来更改AppDelegate
:
@interface AppDelegate : UIResponder <UIApplicationDelegate> {
// ...
@property (retain, nonatomic) User*user;
// ..
不要忘记合成它。
同时将用户的init方法更改为:
- (id)initWithRealName:(NSString *)realNameArgument UserId:(NSString *)userIdArgument
{
self = [super init];
if (self) {
self.realName = realNameArgument;
self.userId = userIdArgument;
}
return self;
}