繁体   English   中英

使一个属性变强,对于objective-c非原子

[英]making one property strong,nonatomic for objective-c

我有一个多视图应用程序,并使用一个对象来跟踪我的登录用户。 我的User.h看起来像这样

@interface User : NSObject

@property (strong, nonatomic) NSDictionary *data;

@property (weak, nonatomic) NSString *uid;
@property (weak, nonatomic) NSString *firstName;
@property (weak, nonatomic) NSString *lastName;
@property (weak, nonatomic) NSString *dob;
@property (weak, nonatomic) NSString *gender;
@property (weak, nonatomic) NSString *avatarURL;
@property (assign, nonatomic) NSInteger status;

- (void)setPropertiesWith:(NSDictionary *)data;

而User.m看起来像这样

#import "User.h"

@implementation User
/*
 * set properties
 */
- (void)setPropertiesWith:(NSDictionary *)data{
    self.data = data;

    self.uid = self.data[@"uid"];
    self.firstName = self.data[@"firstName"];
    self.lastName = self.data[@"lastName"];
    self.dob = self.data[@"dob"];
    self.gender = self.data[@"gender"];
    self.status = [[self.data valueForKeyPath:@"status"] intValue];
    self.avatarURL = self.data[@"avatarURL"];
}

@end

我的数据很弱,但是在其中一种观点中,它会变成空值-我相信ARC正在发布它。 如果我错了,请纠正我。

我有两个问题:

  1. 通过这种设置,数据很strong ,而其他属性weak ,这有潜在的风险吗?

  2. 我应该将数据设为一个ivar,其余数据保持不变吗?

这些属性的存在没有任何实际原因(我的课堂设计技能不佳)。 我只是觉得它很有趣,并想了解发生了什么。

您询问:

  1. 通过这种设置,数据很strong ,而其他属性weak ,这有潜在的风险吗?

是的,如果您nil指定dictionary ,假设您在其他地方没有其他对它们的强引用,那么您的所有属性都可能变为nil

  1. 我应该将数据设为一个ivar,其余数据保持不变吗?

我什至不会将它设为一个ivar(除非还有其他一些要求,但您尚未与我们共享)。 它应该只是一个局部变量,并使您的属性copy (或strong )。


我建议(a)摆脱NSDictionary属性,并(b)使NSString属性成为copy (或strong )而不是weak 另外,我没有定义setPropertiesWith方法,而是定义了一个初始化程序:

// User.h

@interface User : NSObject

@property (copy, nonatomic) NSString *uid;
@property (copy, nonatomic) NSString *firstName;
@property (copy, nonatomic) NSString *lastName;
@property (copy, nonatomic) NSString *dob;
@property (copy, nonatomic) NSString *gender;
@property (copy, nonatomic) NSString *avatarURL;
@property (assign, nonatomic) NSInteger status;

- (instancetype)initWithDictionary:(NSDictionary *)dictionary;

@end

// User.m

@implementation User

- (instancetype)initWithDictionary:(NSDictionary *)dictionary {
    if ((self = [super init])) {
        self.uid       = dictionary[@"uid"];
        self.firstName = dictionary[@"firstName"];
        self.lastName  = dictionary[@"lastName"];
        self.dob       = dictionary[@"dob"];
        self.gender    = dictionary[@"gender"];
        self.status    = [dictionary[@"status"] intValue];
        self.avatarURL = dictionary[@"avatarURL"];
    }

    return self;
}

@end

然后,调用方将执行以下操作:

User *user = [[User alloc] initWithDictionary:someDictionary];

您还可以在这里考虑其他改进(例如, readonly公共接口,声明可空性,字典上的轻量级泛型等),但是以上可能是一个很好的起点。


顺便说一句,如果您想知道为什么我制作这些copy而不是strong ,我们只是想保护自己,以防调用者传递NSMutableString (它是NSString子类)并在以后意外地对其进行了突变。 这只是一个更安全,更防御的模式。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM