从UIViewController更改AppDelegate的属性不起作用

时间:2014-10-23 08:50:29

标签: ios objective-c appdelegate

我遇到了AppDelegate内部的问题,我创建了一个在应用内共享价值的属性。

@property (nonatomic, retain) User *currentUser;

User对象的定义是

@property int points;
@property (nonatomic, copy) NSString *userName;

我有一个UIViewController A,其中一个字段显示当前用户的名字。单击一个按钮将调出UIViewController B并在UIVIewController B内部,我尝试更改值:

// I print out these two values here 1
((AppDelegate*)[UIApplication sharedApplication].delegate).currentUser.userName= @"newName" ;
((AppDelegate*)[UIApplication sharedApplication].delegate).currentUser.points= 19 ;
// I print out these two values here 2

从1和2的打印输出,userName已成功更改。但是,当我将控件从B传回A时,UIViewController A中的userName字段尚未更新。在我的ViewController A中,我有:

- (void)viewWillAppear:(BOOL)animated{
   textField.text = ((AppDelegate*)[UIApplication sharedApplication].delegate).currentUser.userName;
}

有什么想法吗?

此致 锤子


更新

更奇怪的是,第一行打印0,第二行13,第3行0和最后一行13.看起来分配永远不会起作用。用户ID定义为@property int userId;

NSLog(@"BeforeLogin:%d",((AppDelegate*)[UIApplication sharedApplication].delegate).currentUser.userId);
NSLog(@"newUser.userId:%d",newUser.userId);
// update profile locally
((AppDelegate*)[UIApplication sharedApplication].delegate).currentUser.userId= newUser.userId ;
NSLog(@"AfterLogin:%d",((AppDelegate*)[UIApplication sharedApplication].delegate).currentUser.userId);
NSLog(@"newUser.userToken:%@",newUser.userToken);

User.h

#import <Foundation/Foundation.h>
@interface User : NSObject<HttpClientDelegate>
@property int userId; // I also try @property (assign, nonatomic, readwrite) int userId;

1 个答案:

答案 0 :(得分:0)

你应该改变你的属性定义,例如,

这个

@property (nonatomic, copy) NSString *userName;

用这个

@property (nonatomic, strong) NSString *userName;

还要看一下如何定义properties

的示例