在另一个方法中使用viewDidLoad中创建的NSString变量

ada*_*ven 0 variables objective-c instance-variables nsstring ios

在我的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];
Run Code Online (Sandbox Code Playgroud)

我希望能够在另一个方法中使用这些变量(即- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {)

如何在viewDidLoad方法之外重用这些变量?我是新手......帮助会非常感激

小智 7

使它们成为实例变量,而不是您正在使用的方法的本地变量.之后,您可以从同一个类的所有方法访问它们.

例:

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

- (void)viewDidLoad
{
    currentURL = self.URL.absoluteString;
    // etc. same from other methods
}
Run Code Online (Sandbox Code Playgroud)

  • @AdamD就在这里,但是*非常请*如果你是初学者,请阅读Objective-C教程 - 这是非常基本的东西. (4认同)