0

私のviewDidLoad方法では、次の変数を設定します。

// Get requested URL and set to variable currentURL
NSString *currentURL = self.URL.absoluteString;
//NSString *currentURL = mainWebView.request.URL.absoluteString;
NSLog(@"Current url:%@", currentURL);

//Get PDF file name
NSArray *urlArray = [currentURL componentsSeparatedByString:@"/"];
NSString *fullDocumentName = [urlArray lastObject];
NSLog(@"Full doc name:%@", fullDocumentName);

//Get PDF file name without ".pdf"
NSArray *docName = [fullDocumentName componentsSeparatedByString:@"."];
NSString *pdfName = [docName objectAtIndex:0];

これらの変数を別のメソッド内で使用できるようにしたいと思います(つまり- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {

viewDidLoadメソッドの外でこれらの変数を再利用するにはどうすればよいですか?私は初心者です...助けていただければ幸いです

4

4 に答える 4

7

それらを、使用しているメソッドに対してローカルな変数ではなく、インスタンス変数にします。その後、同じクラスのすべてのメソッドからそれらにアクセスできます。

例:

@interface MyClass: NSObject {
    NSString *currentURL;
    // etc.
}

- (void)viewDidLoad
{
    currentURL = self.URL.absoluteString;
    // etc. same from other methods
}
于 2012-08-28T19:40:45.763 に答える
1

viewDidLoadを定義するクラス内の「グローバル変数」(タグが言うように)に関しては、インスタンス変数として作成します。

クラスのあなたの.hで

@interface MyViewController : UIViewController 
{
    NSArray *docName;
    NSString *pdfName;
    ...
}
于 2012-08-28T19:41:12.753 に答える
1

あなたの@interface.hファイルに)これを含めてください:

@property (nonatomic, strong) NSString *currentURL;
// the same for the rest of your variables.

これで、を呼び出すことでこれらのプロパティにアクセスできるようになりますself.currentURL。これが新しいプロジェクトであり、ARCがオンになっている場合は、自分でメモリを管理する必要はありません。

于 2012-08-28T19:44:23.483 に答える
1

H2CO3が示唆するように、それらをインスタンス変数にします。また、actionSheet:clickedButtonAtIndex関数自体ですべての変数を導出することもできます。

必要なすべての変数がself.URL.absoluteStringから派生していることに気付きました。したがって、self.URLは必要なものを保持しているインスタンス変数であるため、すべてのコードを移動しても問題はありません。

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
// Get requested URL and set to variable currentURL
NSString *currentURL = self.URL.absoluteString;
//NSString *currentURL = mainWebView.request.URL.absoluteString;
NSLog(@"Current url:%@", currentURL);

//Get PDF file name
NSArray *urlArray = [currentURL componentsSeparatedByString:@"/"];
NSString *fullDocumentName = [urlArray lastObject];
NSLog(@"Full doc name:%@", fullDocumentName);

//Get PDF file name without ".pdf"
NSArray *docName = [fullDocumentName componentsSeparatedByString:@"."];
NSString *pdfName = [docName objectAtIndex:0];

// Do what you need now...
}
于 2012-08-28T19:44:55.407 に答える