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;
you should change your property definition e.g.,
this
with this
also take a look at the examples how to define properties