V2EX › iDev
在 iOS7 里面,weak,unsafe_unretained 等修饰符的作用去掉了么?为什么自己测试时和书上看到的结果不一样呢?还是我测试的有问题呢?麻烦大家给指点一下了
By lcl22hope at 2014 年 8 月 28 日 · 5339 次点击NSString* test = [NSString stringWithFormat:@"test1"];
NSString __unsafe_unretained *c = test;
NSString __weak *d = test;
test = @“test2”;
NSLog(@"%@",c);
NSLog(@"%@",d);
/////////////////////////////////////////// 不应该是空值么?
2014-08-28 08:14:43.583 TestOnline[191:60b] test1
2014-08-28 08:14:44.665 TestOnline[191:60b] test1
NSString __unsafe_unretained *c = test;
NSString __weak *d = test;
test = @“test2”;
NSLog(@"%@",c);
NSLog(@"%@",d);
/////////////////////////////////////////// 不应该是空值么?
2014-08-28 08:14:43.583 TestOnline[191:60b] test1
2014-08-28 08:14:44.665 TestOnline[191:60b] test1
8 条回复 • 2014-08-28 10:11:55 +08:00
|
1
lcl22hope OP 原来是不应该用NSString来做实验,但确实网上好多帖子都是用NSString来举例的啊,很怀疑他们自己都测没测过,自己写的东西。
// Do any additional setup after loading the view, typically from a nib. NSObject* test = [[NSObject alloc] init]; NSObject __unsafe_unretained *c = test; NSObject __weak *d = test; test = nil; NSLog(@"%@",[c description]);//bad access NSLog(@"%@",[d description]);//d 已经是nil |
|
2
lcl22hope OP 但是问题来了,为什么NSString不行呢?求指教
|
|
4
likid 2014 年 8 月 28 日 编译器会对 NSString 做优化,NSString Class 方法生成的变量会被存储在某个地方(具体忘了在哪里),所以不会被立即释放。
另,这种问题不应该来这么问吧。Stackoverflow 更好 |
|
7
dopcn 2014 年 8 月 28 日 @likid
我看过的是说 NSString 的常量@"test"因为编译器的优化不会立刻释放 而[NSString stringWithFormat:@"test1"]; 等价于 [[[NSString alloc] initWithString:@"test1"] autorelease]; 这种情况下必须等到 autoreleasepool 干掉才会释放 总之用 NSString 做这个确实不合适 |
|
8
66450146 2014 年 8 月 28 日 String literals are optimized that they can be saved in a static memory area that won't be changed.
记住字符串常量的特殊性就好了,从 c-string 到 NSString 都是这样,字符串常量因为使用广泛而且优化效果明显(静态内存区),基本上所有的编译器都会去做这个工作。 |
iOS 开发实用技术导航
NSHipster 中文版
› http://nshipster.cn/
cocos2d 开源 2D 游戏引擎
› http://www.cocos2d-iphone.org/
CocoaPods
› http://cocoapods.org/
Google Analytics for Mobile 统计解决方案
› http://code.google.com/mobile/analytics/
WWDC
› https://developer.apple.com/wwdc/
Design Guides and Resources
› https://developer.apple.com/design/
Transcripts of WWDC sessions
› http://asciiwwdc.com
Cocoa with Love
› http://cocoawithlove.com/
Cocoa Dev Central
› http://cocoadevcentral.com/
NSHipster
› http://nshipster.com/
Style Guides
› Google Objective-C Style Guide
› NYTimes Objective-C Style Guide
Useful Tools and Services
› Charles Web Debugging Proxy
› Smore