Object-C strong和weak的解釋
文章來源:依人網 添加時間:2012-7-5 8:38:31
首先,weak隻能在iOS5中使用,而Object-C中預設是strong模式的。
從我的了解看,有點C++裡面的淺拷貝和深拷貝的意思。
比如
Test * t1 = new Test ( ) ;
Test * t2 = t1 ;
當我們釋放了t1的時候,t2也指向了null.
如果
Test * t2 = DeepCopy (t1 ) ; 如果我們 delete t1 ;
t1 = null ; 後,t2實際還是有值的。 在Object-C中,使用Strong相當于深拷貝,而weak相當于弱拷貝。代碼示範如下: #import <UIKit/UIKit.h>
@interface Moving_from_Manual_Reference_Counting_to_ARCAppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic ) UIWindow *window;
@property (nonatomic, strong ) NSString *string1;
@property (nonatomic, strong ) NSString *string2;
@end
import "Moving_from_Manual_Reference_Counting_to_ARCAppDelegate.h"
@implementation Moving_from_Manual_Reference_Counting_to_ARCAppDelegate
@synthesize window = _window;
@synthesize string1; @synthesize string2;
- (BOOL) application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
self.string1 = @"String 1";
self.string2 = self.string1;
self.string1 = nil;
NSLog(@"String 2 = %@", self.string2);
self.window = [[UIWindow alloc] initWithFrame: [[UIScreen mainScreen] bounds]];
self.window.backgroundColor = [UIColor whiteColor]; [self.window makeKeyAndVisible];
return YES;
}
如果代碼
#import <UIKit/UIKit.h>
@interface Moving_from_Manual_Reference_Counting_to_ARCAppDelegate : UIResponder <UIApplicationDelegate>
@property (weak, nonatomic ) UIWindow *window;
@property (nonatomic, weak ) NSString *string1;
@property (nonatomic, weak ) NSString *string2;
@end #import "Moving_from_Manual_Reference_Counting_to_ARCAppDelegate.h"
@implementation Moving_from_Manual_Reference_Counting_to_ARCAppDelegate
@synthesize window = _window;
@synthesize string1; @synthesize string2;
- ( BOOL ) application : (UIApplication * )application didFinishLaunchingWithOptions : ( NSDictionary * )launchOptions {
self.string1 = @ "String 1";
self.string2 = self.string1;
self.string1 = nil;
//下面的string2已經沒有值了。
NSLog ( @ "String 2 = %@", self.string2 );
self.window = [ [UIWindow alloc ] initWithFrame : [ [UIScreen mainScreen ] bounds ] ];
self.window.backgroundColor = [UIColor whiteColor ]; [self.window makeKeyAndVisible ];
return YES;
}