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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值