在 iOS7 里面,weak,unsafe_unretained 等修饰符的作用去掉了么?为什么自己测试时和书上看到的结果不一样呢?还是我测试的有问题呢?麻烦大家给指点一下了

2014-08-28 08:33:45 +08:00
 lcl22hope
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
4520 次点击
所在节点    iDev
8 条回复
lcl22hope
2014-08-28 08:54:06 +08:00
原来是不应该用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
lcl22hope
2014-08-28 08:55:47 +08:00
但是问题来了,为什么NSString不行呢?求指教
cielpy
2014-08-28 09:12:30 +08:00
@lcl22hope Google一下 关键字 NSString 内存 应该有你想了解的。
likid
2014-08-28 09:16:40 +08:00
编译器会对 NSString 做优化,NSString Class 方法生成的变量会被存储在某个地方(具体忘了在哪里),所以不会被立即释放。
另,这种问题不应该来这么问吧。Stackoverflow 更好
lcl22hope
2014-08-28 09:20:48 +08:00
@likid 谢谢回答,后来是在stackoverflow上得到启示,具体我在google下,多谢指点
lcl22hope
2014-08-28 09:21:41 +08:00
@cielpy 好的,谢谢指点,我去谷歌了解下
dopcn
2014-08-28 09:38:30 +08:00
@likid
我看过的是说 NSString 的常量@"test"因为编译器的优化不会立刻释放
而[NSString stringWithFormat:@"test1"];
等价于
[[[NSString alloc] initWithString:@"test1"] autorelease];
这种情况下必须等到 autoreleasepool 干掉才会释放

总之用 NSString 做这个确实不合适
66450146
2014-08-28 10:11:55 +08:00
String literals are optimized that they can be saved in a static memory area that won't be changed.

记住字符串常量的特殊性就好了,从 c-string 到 NSString 都是这样,字符串常量因为使用广泛而且优化效果明显(静态内存区),基本上所有的编译器都会去做这个工作。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/130327

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX