【发布时间】:2015-03-23 06:55:55
【问题描述】:
为什么temp 对象没有被释放并设置为零,即使它被声明为__week。但是如果是 Person 对象,它会按预期工作。 NSString 对象内存生命周期的处理方式是否不同?怎么样?
@interface Person : NSObject
@property(nonatomic, strong) NSString *name;
- (instancetype)initWithName:(NSString *)name;
+ (Person *)personWithName:(NSString *)name;
@end
@implementation Person
- (instancetype)initWithName:(NSString *)name {
if (self = [super init]) {
self.name = name;
}
return self;
}
+ (Person *)personWithName:(NSString *)name {
return [[self alloc] initWithName: name];
}
@end
- (void)viewDidLoad {
__weak NSString *temp;
@autoreleasepool {
NSMutableArray *data = [[NSMutableArray alloc] initWithObjects:@"firstString", @"secondString", nil];
temp = data[0];
[data removeObjectAtIndex:0];
}
NSLog(@"%@", temp);//prints firstString instead of null
__weak Person *person ;
@autoreleasepool {
NSMutableArray *persons = [[NSMutableArray alloc] initWithObjects:[Person personWithName:@"Steve"], [Person personWithName:@"Harry"], nil];
person = persons[0];
[persons removeObjectAtIndex:0];
}
NSLog(@"%@", person.name);//prints null as expected because person object will be deallocated,
}
【问题讨论】:
-
尝试记录 person 对象,检查是否给你 null。 NSLog(@"%@", 人);
-
这可能是因为您正在使用常量字符串进行测试。尝试构建
NSString对象,看看是否可行。
标签: objective-c automatic-ref-counting