在块内设置 属性 是否安全
Is this safe to set property inside a block
我是从iOS 8开始接触Objective-C的新手,所以对ARC略知一二,我的代码在ARC下。
假设我有一个 class UserModel 具有 NSArray 和 NSString 等属性。我有 initWithDataSource:data 来分配初始化一个 UserModel。
从内存角度来看,设置一个 属性 内部块是否安全?我觉得我的代码会导致任何保留周期。想知道我应该使用 weak self 还是其他东西来设置 属性?
//在HomeViewController.m
@interface HomeViewController() <UICollectionViewDataSource>
@property (strong, nonatomic) IBOutlet UILabel *HomeLabel;
@property (strong, nonatomic) IBOutlet UICollectionView *ProjectCollectionView;
@property (strong, nonatomic) UserModel * HomeViewUserModel;
@end
/**
* fetch latest projects from remote side
*/
- (void) fetchUserModelFromRemote {
[MySharedInstance getProjectDataOnSuccess:^(id result) {
NSDictionary *data = result[@"data"];
self.HomeViewUserModel = [[UserModel alloc] initWithDataSource:data];
[[NSNotificationCenter defaultCenter] postNotificationName:@"alertCountUpdate" object:self userInfo:@{@"count": (NSNumber *)data[@"unread"]}];
}onFailure:^(id error) {}];
[MyCache cacheProjectListWithData:self.HomeViewUserModel];
}
只有在 self
保留对其访问的块的引用时才应该是个问题。但是如果你想安全起见,就在块外,你可以将 self 类型的弱变量分配给self,以便您访问 self 的弱版本,从而减轻任何疑问,例如:
__weak TypeOfSelf weakSelf = self;
//use weakSelf in block
也可能添加一些 nil 检查以确保在对它做任何事情之前它仍然存在
您的担忧是有道理的,但没有保留周期:
匿名块将不会被 self
本身引用 - 因此,没有循环引用。
另请参阅:Using weak self in dispatch_async function
我是从iOS 8开始接触Objective-C的新手,所以对ARC略知一二,我的代码在ARC下。
假设我有一个 class UserModel 具有 NSArray 和 NSString 等属性。我有 initWithDataSource:data 来分配初始化一个 UserModel。
从内存角度来看,设置一个 属性 内部块是否安全?我觉得我的代码会导致任何保留周期。想知道我应该使用 weak self 还是其他东西来设置 属性?
//在HomeViewController.m
@interface HomeViewController() <UICollectionViewDataSource>
@property (strong, nonatomic) IBOutlet UILabel *HomeLabel;
@property (strong, nonatomic) IBOutlet UICollectionView *ProjectCollectionView;
@property (strong, nonatomic) UserModel * HomeViewUserModel;
@end
/**
* fetch latest projects from remote side
*/
- (void) fetchUserModelFromRemote {
[MySharedInstance getProjectDataOnSuccess:^(id result) {
NSDictionary *data = result[@"data"];
self.HomeViewUserModel = [[UserModel alloc] initWithDataSource:data];
[[NSNotificationCenter defaultCenter] postNotificationName:@"alertCountUpdate" object:self userInfo:@{@"count": (NSNumber *)data[@"unread"]}];
}onFailure:^(id error) {}];
[MyCache cacheProjectListWithData:self.HomeViewUserModel];
}
只有在 self
保留对其访问的块的引用时才应该是个问题。但是如果你想安全起见,就在块外,你可以将 self 类型的弱变量分配给self,以便您访问 self 的弱版本,从而减轻任何疑问,例如:
__weak TypeOfSelf weakSelf = self;
//use weakSelf in block
也可能添加一些 nil 检查以确保在对它做任何事情之前它仍然存在
您的担忧是有道理的,但没有保留周期:
匿名块将不会被 self
本身引用 - 因此,没有循环引用。
另请参阅:Using weak self in dispatch_async function