为什么这段代码有效:
NSNumber *a = [[NSNumber alloc] initWithInt:5];
[a release];
NSLog(@"%i", [a intValue]);// it shows 5. why???
消息 intValue
被发送到已释放的对象。它的引用计数必须为0。这是怎么回事?
最佳答案
我认为 NSNumber 有一个特殊的实现,就像 NSString 一样。
[NSNumber alloc] 实际上并不分配内存,而是返回一个通用指针。分配将由 init 方法之一处理,但 initWithInt:5 也是一种常见情况,它不是创建新对象,而是返回指向默认对象的指针。而且这个无论如何也不能发布。
// do it once
NSNumber* five1 = [NSNumber alloc];
NSLog(@"%p", five1);
five1 = [five1 initWithInt:5];
NSLog(@"%p", five1);
// and once more
NSNumber* five2 = [NSNumber alloc];
NSLog(@"%p", five2);
five2 = [five2 initWithInt:5];
NSLog(@"%p", five2);
事实上,多次发送release消息应该没有问题:
[five1 release];
[five1 release];
[five1 release];
关于objective-c - 为什么它不崩溃?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9860859/