【发布时间】:2016-10-11 15:00:32
【问题描述】:
我正在做这个简单的 Objective-C 练习来更好地理解 ARC,它是一个程序,当引用设置为强时应该显示 R2D2,而当引用设置为弱时会失败。但是,代码仍然可以编译,即使有警告说对象将被释放。
main.m
#import <Foundation/Foundation.h>
#import "Robot.h"
int main(int argc, const char * argv[])
{
@autoreleasepool {
Robot *robot = [[Robot alloc]init];
robot.firstString =[[NSString alloc]initWithFormat:@"R%d",2];
robot.secondString = [[NSString alloc]initWithFormat:@"D%d",2];
NSLog(@"%@%@",robot.firstString,robot.secondString);
}
return 0;
}
Robot.m
#import "Robot.h"
@implementation Robot
@end
Robot.h
#import <Foundation/Foundation.h>
@interface Robot : NSObject
@property (strong) NSString *firstString;
@property (weak) NSString *secondString;
@end
谢谢
【问题讨论】:
-
你对“失败”的定义是什么?更糟糕的情况是你会看到
(null)而不是D2。结果也可能受到编译时优化级别的影响。 -
@rmaddy 这是另一个使用系统类来尝试探索运行时行为的案例。在这种情况下,绊倒标记的指针。一般来说,在探索运行时时,最好从您自己的
NSObject子类开始,这样您就不会对NS*类的实现细节感到惊讶。
标签: objective-c automatic-ref-counting objective-c-runtime