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

Objective c 在另一个方法中使用viewDidLoad中创建的NSString变量,objective-c,ios,variables,nsstring,instance-variables,Objective C,Ios,Variables,Nsstring,Instance Variables,在我的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 nam

在我的
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 ClickedButtonIndex:(NSInteger)buttonIndex{

如何在viewDidLoad方法之外重用这些变量?我是一个新手…非常感谢您的帮助

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

例如:

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

- (void)viewDidLoad
{
    currentURL = self.URL.absoluteString;
    // etc. same from other methods
}
在定义viewDidLoad的类中,根据“全局变量”(如标记所述)将它们创建为实例变量

在你的课堂上

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

@界面
(在
.h
文件中)包括以下内容:

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

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

按照H2CO3的建议将它们设为实例变量。此外,您还可以在操作表中派生所有变量:ClickedButtonIndex函数本身。

我注意到所有必需的变量都是从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...
}

请使用正确的术语和语言。它们既不是全局变量,也不是即时变量。它们被称为实例变量。@H2CO3对不起,这只是实例变量的输入错误。谢谢你告诉我。“全局变量”我在引号中提到,因为这是指标记。@AdamD在这里,但如果你是初学者,请阅读Objective-C教程-这是非常基本的东西。