簡體   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