从 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);
用户.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;
另请查看如何定义属性
这篇关于从 UIViewController 更改 AppDelegate 的属性不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!