天天看点

Object-C strong和weak的解释

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;

}

继续阅读