Change property of AppDelegate from UIViewController is not working

耗尽温柔 提交于 2019-12-12 23:17:21

问题


I run into an issue that inside of AppDelegate, I create a property to share value within the app.

@property (nonatomic, retain) User *currentUser;

The definition of User object is

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

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

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;
}

Any ideas?

Regards Hammer


UPDATE

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;

回答1:


you should change your property definition e.g.,

this

@property (nonatomic, copy) NSString *userName;

with this

@property (nonatomic, strong) NSString *userName;

also take a look at the examples how to define properties



来源:https://stackoverflow.com/questions/26524445/change-property-of-appdelegate-from-uiviewcontroller-is-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!