Why temp
即使对象被声明为,也不会被释放并设置为 nil__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,
}
常量字符串永远不会被释放。还有其他对象永远不会被释放,例如某些 NSNumber 对象(在 64 位版本上,大多数 NSNumber 对象)。
这让我想知道你在做什么。如果 NSString* 变成 nil (它不会),你想做什么?
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)