當前位置:成語大全網 - 新華字典 - retain和strong,assign和weak的區別

retain和strong,assign和weak的區別

strong與weak是由ARC新引入的對象變量屬性

xcode 4.2(ios sdk4.3和以下版本)和之前的版本使用的是retain和assign,是不支持ARC的。xcode 4.3(ios5和以上版本)之後就有了ARC,並且開始使用

strong與weak

assign: 用於非指針變量。用於

基礎數據類型 (例如NSInteger)和C數據類型(int, float, double, char, 等),另外還有id

如:

@property (nonatomic, assign) int number;

@property (nonatomic, assign) id className;//id必須用assign

反正記住:前面不需要加 “*” 的就用assign吧

retain:用於指針變量。就是說妳定義了壹個變量,然後這個變量在程序的運行過程中會被更改,並且影響到其他方法。壹般是用於字符串( NSString,NSMutableString),數組(NSMutableArray,NSArray),字典對象,視圖對象(UIView ),控制器對象(UIViewController)等

比如:

@property (nonatomic,retain) NSString * myString;

@property (nonatomic, retain) UIView * myView;

@property (nonatomic, retain) UIViewController * myViewController;

xcode 4.2不支持ARC,所以會頻繁使用retain來修飾,用完釋放掉,而xcode4.3支持ARC,可以使用retian,不需要手動釋放內存,系統會自動為妳完成,如果妳在xcode4.3上面開發,retian和strong都是壹樣的,沒區別

strong和weak:

事實上

@property(nonatomic,strong) MyClass *myObject;就是相當於@property(nonatomic,retain) MyClass *myObject;@property(nonatomic, weak )id<RNNewsFeedCellDelegate>delegate;就是相當於@property(nonatomic,assign )id<RNNewsFeedCellDelegate>delegate;

現在系統自動生成的屬性都是用weak來修飾的,我想應該是xcode 4.2不支持ARC,所以大家都是用retain。現在xcode4.3支持ARC了,於是蘋果建議程序員放棄retain,以後都用weak。

weak 就是相當於assign,同樣可以在xcode4.3開發環境下放棄使用assign 使用weak 來代替

unsafe_unretained

unsafe_unretained 就是ios5版本以下的 assign ,也就是 unsafe_unretained , weak, assign 三個都是壹個樣的。 因為 ios5用的是 weak ,那在ios4.3就用不了,如果妳將 weak 修改為 unsafe_unretained ,那就可以用了。說到底就是iOS 5之前的系統用該屬性代替 weak 來使用。

copy:這個東西估計是大部分人最不容易搞明白的東西,我也搞不明白。聽別人說這個東西基本不用了,效果其實和retain沒什麽兩樣,唯壹的區別就是copy只用於NSString而不能用於NSMutableString。

不過好像當壹個類繼承NSObject,那麽這個類裏面的屬性需要使用copy,比如:

#import <Foundation/Foundation.h>

#import <MapKit/MKAnnotation.h>

@interface Annotation : NSObject <MKAnnotation> {

CLLocationCoordinate2D coordinate;

NSString *title;

NSString *subtitle;

}

@property (nonatomic) CLLocationCoordinate2D coordinate;

@property (nonatomic, copy) NSString *title;

@property (nonatomic, copy) NSString *subtitle;

@end

反正以後就這麽用就是了

反正就記住壹點:xcode4.2用retain和assign ;xcode4.3或以上版本用strong與weak 。