[英]Path to file is modified by another view controller
我有2個將請求發送到Web服務的視圖控制器。 接收到數據后,數據將保存到“文檔”文件夾中的文件中。
這些是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
之所以得到此結果,是因為您將“路徑”設置為文件頂部,從而使其成為全局變量。 用花括號將其包圍,然后它將是一個普通的ivar,
@implementation FV_Today_ViewController {
NSArray *paths;
NSString *documentsDirectory;
NSString *path;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.