从UIViewController更改AppDelegate的属性不起作用 [英] Change property of AppDelegate from UIViewController is not working
问题描述
我遇到一个问题,在AppDelegate
内部,我创建了一个属性以在应用程序内共享价值.
I run into an issue that inside of AppDelegate
, I create a property to share value within the app.
@property (nonatomic, retain) User *currentUser;
User
对象的定义是
@property int points;
@property (nonatomic, copy) NSString *userName;
我有一个UIViewController A,其中一个字段显示当前用户的名称.单击一个按钮将调出UIViewController B并在UIVIewController B内部,我尝试更改值:
I have a UIViewController A with a field displaying current user's name. Click on a button will bring up UIViewController B and inside of UIVIewController B, I try to change the values:
// 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中,我有:
From the print out at 1 and 2, the userName
has been changed successfully. However, when I pass the control back to A from B, the userName
field in UIViewController A has not been updated. In my ViewController A, I have:
- (void)viewWillAppear:(BOOL)animated{
textField.text = ((AppDelegate*)[UIApplication sharedApplication].delegate).currentUser.userName;
}
有什么想法吗?
问候 锤子
更奇怪的是,第一行打印0,第二行13,第三行0,最后一行13.看起来分配永远都行不通.用户ID定义为@property int userId;
.
it is more weird that, the first line prints 0, second line 13, 3rd line 0 and the last line 13. It looks like the assignment never works. User ID is defined as @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;
推荐答案
您应更改属性定义,例如
you should change your property definition e.g.,
此
@property (nonatomic, copy) NSString *userName;
与此
@property (nonatomic, strong) NSString *userName;
还查看了如何定义属性的示例
also take a look at the examples how to define properties
这篇关于从UIViewController更改AppDelegate的属性不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!