我有一个单独的网络类以及需要在我的应用程序中保留的单例对象。单例是根据从Web调用中检索到的数据进行初始化的,所以现在我的代码正常工作,我的单例网络类中有以下内容:
- (void)initializeObjectWithSuccess:(void (^)(BOOL))success
failure:(void (^)(NSError *error))failure {
[self.HTTPClient postPath:[NSString stringWithFormat:@"users/%@/", [CPUser sharedUser].name parameters:[self createParameters] success:^(AFHTTPRequestOperation *operation, id responseObject) {
id json = [NSJSONSerialization JSONObjectWithData:responseObject
options:NSJSONReadingAllowFragments
error:nil];
[[CPList sharedList] setIdentifier:json[@"id"]];
[[CPList sharedList] setImages:json[@"images"]];
if (success) {
success(YES);
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
failure(error);
}];
}
我不知道如何在我的单例CPList中初始化我需要的所有属性而不在此方法中设置它们,但是我知道这不是正确的封装,因为CPRequestManager类应该对CPList类一无所知
答案 0 :(得分:1)
如果您的问题是,您不希望此课程知道CPList
的名称及其单身人士的详细信息,并且可以使用+[CPList sharedInstance]
访问该名称你可以传入一个符合协议的对象。这基本上将单身人士的知识移到其他地方
- (void)initializeObjectWithList:(id<CPList>)list
success:(void (^)(BOOL))success
failure:(void (^)(NSError *error))failure;
{
[self.HTTPClient postPath:[NSString stringWithFormat:@"users/%@/", [CPUser sharedUser].name parameters:[self createParameters] success:^(AFHTTPRequestOperation *operation, id responseObject) {
id json = [NSJSONSerialization JSONObjectWithData:responseObject
options:NSJSONReadingAllowFragments
error:nil];
[list setIdentifier:json[@"id"]];
[list setImages:json[@"images"]];
if (success) {
success(YES);
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
failure(error);
}];
}
或者您可以删除所有知识,其中包含&#34;列表&#34;只需让这个方法返回实际数据,然后调用者就可以在列表中设置它
- (void)initializeObjectWithSuccess:(void (^)(NSString *ID, NSArray *images))success
failure:(void (^)(NSError *error))failure;
{
[self.HTTPClient postPath:[NSString stringWithFormat:@"users/%@/", [CPUser sharedUser].name parameters:[self createParameters] success:^(AFHTTPRequestOperation *operation, id responseObject) {
id json = [NSJSONSerialization JSONObjectWithData:responseObject
options:NSJSONReadingAllowFragments
error:nil];
if (success) {
success(json[@"id"], json[@"images"]);
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
failure(error);
}];
}
如果没有任何进一步的背景,很难提出结构性变化,但这里有两个潜在的重构,可能会让你思考你所做的事情