跳到主要內容

發表文章

目前顯示的是 2018的文章

NSString 該用 copy 還是 strong

先做個實驗, NSString 的 copy 會不會讓 reference count + 1呢? 事實證明 NSString 的 copy 會讓原本 object count +1,而 NSMutableString 不會,原因是如果一直用 copy 會有效能問題,所以 NSString 的 copy 預設是 retain count + 1 However, you may think that always  copy ing is slow. So  NSString 's  copy  simply calls  retain .  NSMutableString 's  copy  makes an actual copy. NSString   NSMutableString 所以 NSString 到底是用 copy or strong 呢?  如上圖所示,應該取決於你是否會用 Mutable 的情況,一般來說用 copy 是比較保險的, 因為可能會是 NSString instance 或 NSMutableString instance ,在 mutable 情況也不會有問題。 -end- (番外篇) 那 NSArray NSMutableArray 的 @property 該怎麼用呢? NSArray 用 copy or string 是情況而定,取決於是否要跟著改值 NSMutableArray 則是用 strong ,因為 mutable call copy 會回 immutable counterparts 所以是 NSArray ,如果在 call addObject() 會讓 complier 視為 NSArray 會導致 crash。