如何在xcode中有效地编写类似的代码?

时间:2015-08-19 07:56:13

标签: ios objective-c macros

示例1:

- (NSString *)userToken
{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    return [userDefaults objectForKey:@"userToken"];
}

- (void)setUserToken:(NSString *)userToken
{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults setObject:userToken forKey:@"userToken"];
}

- (NSString *)userName
{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    return [userDefaults objectForKey:@"userName"];
}

- (void)setUserName:(NSString *)userName
{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults setObject:userName forKey:@"userName"];
    [userDefaults synchronize];
}

这些getter和setter非常相似。是否有一个聪明的“宏”可以帮助我简化代码?所以我将能够为每个属性编写几个代码,如下所示:

XXXX(userToken)
XXXX(userName)

示例2:

+ (MyManager *)sharedManager {
    // singleton
    ...
}

- (void)updateName:(NSString *)name {
    self.name = name;
}

+ (void)updateName:(NSString *)name {
    return [[self sharedManager] updateName:name];
}

- (void)updateUid:(NSString *)uid {
    self.uid = uid;
}

+ (void)updateUid:(NSString *)uid {
    return [[self sharedManager] updateUid:uid];
}

我想要一种有效写作的方法。

我该怎么办?

0 个答案:

没有答案