In my viewDidLoad
method, I set the following variables:
// 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];
I would like to be able to use these variables inside of another method (i.e. - (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
)
How can I reuse these variables outside of the viewDidLoad method? I'm a newbie... help would be SO much appreciated
Make them an instance variable and not a variable local to the method you're using. After that, you can access them from all methods of the same class.
Example:
@interface MyClass: NSObject {
NSString *currentURL;
// etc.
}
- (void)viewDidLoad
{
currentURL = self.URL.absoluteString;
// etc. same from other methods
}
In terms of "global-variables" (as you tag says) within your class where you define the viewDidLoad create them as instance variables.
In your .h of the class
@interface MyViewController : UIViewController
{
NSArray *docName;
NSString *pdfName;
...
}
In your @interface
(in the .h
file) include this:
@property (nonatomic, strong) NSString *currentURL;
// the same for the rest of your variables.
Now you'll be able to access these properties by calling self.currentURL
. If this is a newer project and ARC is turned on you don't have to bother with managing memory yourself.
Make them instance variable as H2CO3 suggests. Also you could just derive all your variables in the actionSheet:clickedButtonAtIndex function itself.
I notice that all the required variables are derived from self.URL.absoluteString. Therefore there should be no problem moving all your code, because self.URL is your instance variable that is holding what you want.
- (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...
}