我有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
Today_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("路径")来存储路径,但问题在于" sendMonthRequest"方法(Live_VC)路径的值是在另一个VC(Today_VC)中设置的值。 怎么可能?如何通过第二个VC改变第一个VC中的NSString的值?
谢谢, 的Corrado
答案 0 :(得分:0)
您获得此结果是因为您将“path”设置为文件顶部的全局变量。用花括号环绕它,然后它将是一个普通的ivar,
@implementation FV_Today_ViewController {
NSArray *paths;
NSString *documentsDirectory;
NSString *path;
}