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

在我的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方法之外重用这些变量? 我是新手……非常感谢帮助

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

例:

 @interface MyClass: NSObject { NSString *currentURL; // etc. } - (void)viewDidLoad { currentURL = self.URL.absoluteString; // etc. same from other methods } 

对于您定义viewDidLoad的类中的“全局变量”(如标记所示),将它们创建为实例变量。

在你class上的.h

 @interface MyViewController : UIViewController { NSArray *docName; NSString *pdfName; ... } 

@interface (在.h文件中)包括:

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

现在,您可以通过调用self.currentURL来访问这些属性。 如果这是一个较新的项目并且ARC已打开,则您不必费心自行管理内存。

如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... }