我有 2 个向 Web 服务发送请求的视图控制器。接收到数据后,数据将保存到 Document 文件夹中的文件中。
这些是2个VC:
Live_VC:
#import "FV_Live_ViewController.h"
@interface FV_Live_ViewController ()
@end
@implementation FV_Live_ViewController
NSArray *paths;
NSString *documentsDirectory;
NSString *path;
- (void)viewDidLoad {
paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
documentsDirectory = [paths firstObject];
[self sendRequest]; // first request of data ("Live" data)
}
- (void)sendRequest {
// other code
// request of "Live" data
[urlRequest startWithCompletion:^(URLRequest *request, NSData *data, NSError *error, BOOL success) {
if (success) {
// other code
NSString *filename = [NSString stringWithFormat:@"months.plist"];
path = [documentsDirectory stringByAppendingPathComponent:filename]; // path = "...\months.plist"
// second request of data (monthly data) if months.plist doesn't exists
if (![[NSFileManager defaultManager] fileExistsAtPath: path]) {
[self sendMonthRequest];
}
}
}];
}
- (void)sendMonthRequest {
[urlRequest startWithCompletion:^(URLRequest *request, NSData *data, NSError *error, BOOL success) {
if (success) {
// other code
[monthlyArray writeToFile: path atomically:YES]; // path should be "...\months.plist" while it is "...\yesterday.plist"
}
}];
}
@end
今天_VC:
#import "FV_Today_ViewController.h"
@interface FV_Today_ViewController ()
@end
@implementation FV_Today_ViewController
NSArray *paths;
NSString *documentsDirectory;
NSString *path;
- (void)viewDidLoad {
paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
documentsDirectory = [paths firstObject];
[self sendRequest]; // first call of "sendRequest" to get today data
}
- (void)sendRequest {
// other code
// request of "Today" data
[urlRequest startWithCompletion:^(URLRequest *request, NSData *data, NSError *error, BOOL success) {
if (success) {
// other code
NSString *filename = [NSString stringWithFormat:@"today.plist"];
path = [documentsDirectory stringByAppendingPathComponent:filename]; // path = "...\today.plist"
[dataDictionary writeToFile: path atomically:YES]; // save data to today.plist
// second call of "sendRequest" to get yesterday data only if yesterday.plist doesn't already exists)
filename = [NSString stringWithFormat:@"yesterday.plist"];
path = [documentsDirectory stringByAppendingPathComponent:filename]; // path = "...\yesterday.plist"
if (![[NSFileManager defaultManager] fileExistsAtPath:path])
[self sendRequest];
}
}];
}
@end
在每个 VC 中,我使用 NSString(“path”)来存储路径,但问题是在“sendMonthRequest”方法(Live_VC)中,路径的值是在另一个 VC(Today_VC)中设置的值。怎么可能?第一个 VC 中的 NSString 的值如何被第二个 VC 更改?
谢谢, 科拉多