我有兩個類:超類,用戶及其子類,UserSession。用戶是非常簡單的,只是對於一些instanceVariables容器:對於高德Objective-C設置/訪問單例類超類中的iVars
//User.h
@interface User : NSObject
- (id)initWithJSON:(NSDictionary *)JSONDictionary;
-(NSNumber *)getUserID;
-(NSString *)getUserName;
-(NSString *)getUserUsername;
-(NSString *)getUserEmail;
-(NSString *)getUserBio;
-(void)setUserID:(NSNumber *)userID;
-(void)setUserName:(NSString *)userName;
-(void)setUserUsername:(NSString *)userUsername;
-(void)setUserEmail:(NSString *)userEmail;
-(void)setUserBio:(NSString *)userBio;
@end
和
//User.m
@interface User()
@end
@implementation User
NSNumber *_userID;
NSString *_userName;
NSString *_userUsername;
NSString *_userEmail;
NSString *_userBio;
- (id)initWithJSON:(NSDictionary *)JSONDictionary
{
self = [super init];
if (!self)
return nil;
_userID = JSONDictionary[@"userID"];
_userName = JSONDictionary[@"userName"];
_userUsername = JSONDictionary[@"userUsername"];
_userEmail = JSONDictionary[@"userEmail"];
_userBio = JSONDictionary[@"userBio"];
return self;
}
加上相關getter和setter方法。
UserSession是一個單例類的子類用戶:
//UserSession.m
@interface UserSession()
@end
@implementation UserSession
static UserSession *_session = nil;
-(void)updateUserForUserSessionWithParams:(NSDictionary *)params
{
[self setUserID:params[@"userId"]];
[self setUserName:params[@"userName"]];
[self setUserUsername:params[@"userUsername"]];
[self setUserEmail:params[@"userEmail"]];
[self setUserBio:params[@"userBio"]];
}
+ (instancetype)sharedSession
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
// Create a session
_session = [[UserSession alloc] init];
});
return _session;
}
繼承人的問題:當我撥打電話一樣
[[UserSession sharedSession]
updateUserForUserSessionWithParams:@{@"userId":@1],
@"userName":@"Steve Smith",
@"userUsername":responseObject[@"ssmith"],
@"userEmail":responseObject[@"[email protected]"],
@"userBio":responseObject[@"I'm steve smith"]}];
,然後在別處:
NSString* stringName = [[UserSession sharedSession] getUserName];
NSString* stringUsername = [[UserSession sharedSession] getUserUsername];
NSString* stringBio = [[UserSession sharedSession] getUserBio];
這些干將回報零!
對不起所有的代碼,但我認爲我在做一些愚蠢的錯誤。任何幫助將是驚人的。
在此先感謝!
我想我們需要看一個setter和getter的例子,但有人不得不想知道爲什麼當你可以簡單地使用Objective-C屬性時自己寫這些東西? '@property NSNumber * userID;'會做到這一點,併爲您節省大量代碼。另外,我們需要看到' - [UserSession init]'方法。 – Caleb 2014-09-02 17:31:40
ObjectiveC還是新的,所以我只是爲了自己的理智而自己寫它們。我不認爲這真的很重要。但我沒有 - [UserSession init]。我會在那裏放什麼? – 2014-09-02 17:42:46