-->

改变从UIViewController的AppDelegate中的属性不工作(Change prop

2019-10-21 03:56发布

我遇到一个问题,里面AppDelegate ,我创建的应用程序中共享值的属性。

@property (nonatomic, retain) User *currentUser;

的定义User对象是

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

我有显示当前用户的名称字段一个UIViewController一个。 点击一个按钮,将弹出的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,将userName在UIViewController中的字段尚未更新。 在我的ViewController A,我有:

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

有任何想法吗?

问候锤


UPDATE

更奇怪的是,第一行打印0,第二行13,第三行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;

Answer 1:

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

这个

@property (nonatomic, copy) NSString *userName;

有了这个

@property (nonatomic, strong) NSString *userName;

也看看例子如何定义属性



文章来源: Change property of AppDelegate from UIViewController is not working