IOS:NSString的发布没有按预期工作 [英] IOS: Release for NSString is not working as expected

查看:136
本文介绍了IOS:NSString的发布没有按预期工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现了NSString的奇怪行为。我尝试运行下面的代码并注意到这一点。

I found a strange behavior with NSString. I tried to run the below code and noticed this.

NSString *str = [[NSString alloc] initwithstring : @"hello"];
[str release];
NSLog(@" Print the value : %@", str);

这里,在第三行应用程序应该崩溃,因为我们正在访问一个被释放的对象。但它印刷了str的价值。它没有崩溃。但是对于NSArray,我发现了不同的行为。

Here, in the third line app should crash because we are accessing an object which is released. But it is printing the value of str. It is not crashing. But with NSArray i observed different behavior.

NSArray *array = [[NSArray alloc] initwithobjects : @"1",  @"2", nil];
[array release];
NSLog(@"Print : %@", [array objectatindex : 0]);
NSLog(@"Print : %@", [array objectatindex : 0]);

代码有两个用于NSArray的NSLog语句。在执行第一个NSLog后释放,这是打印值。但是当第二个NSLog被执行时,应用程序崩溃了。应用程序崩溃是可以接受的,因为访问的数组已经发布但是当第一个NSLog执行时它应该崩溃。不是第二个。

The code has two NSLog statements used for NSArray. Here after releasing when the first NSLog is executed, it is printing value. But when second NSLog is executed, app crashes. App crash is acceptable because the array accessed was released already. But it should crash when the first NSLog is executed. Not the second one.

帮助我解决这个问题。在这些情况下如何发布。

Help me with this behaviors. How release works in these cases.

谢谢
Jithen

Thanks Jithen

推荐答案

第一个示例不会崩溃,因为永远不会释放字符串文字。代码实际上是:

The first example doesn't crash because string literals are never released. The code is really:

NSString *str = @"hello";
[str release];

人们在内存管理上被字符串文字烧毁而错误地使用 == 比较它们而不是 isEqualToString:。编译器进行了一些优化,导致误导性结果。

People get burned with string literals on memory management and mistakenly using == to compare them instead of isEqualToString:. The compiler does some optimizations that lead to misleading results.

更新

以下代码证明了我的观点:

The following code proves my point:

    NSString *literal = @"foo";
    NSString *second = [NSString stringWithString:literal];
    NSString *third = [NSString stringWithString:@"foo"]; // <-- this gives a compiler warning for being redundant
    NSLog(@"literal = %p", literal);
    NSLog(@"second = %p", second);
    NSLog(@"third = %p", third);

此代码提供以下输出:


2013-02-28 22:03:35.663 SelCast [85617:11303] literal = 0x359c

2013-02-28 22:03:35.666 SelCast [85617:11303] second = 0x359c

2013-02-28 22:03:35.668 SelCast [85617:11303] third = 0x359c

2013-02-28 22:03:35.663 SelCast[85617:11303] literal = 0x359c
2013-02-28 22:03:35.666 SelCast[85617:11303] second = 0x359c
2013-02-28 22:03:35.668 SelCast[85617:11303] third = 0x359c



<请注意,所有三个变量都指向同一个内存。

Notice that all three variable point to the same memory.

这篇关于IOS:NSString的发布没有按预期工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆