将NSURL从一个类传递到另一个类

时间:2012-11-24 03:25:20

标签: ios cocoa-touch

在didFinishLaunchingWithOptions的appDelegate中,我有以下内容:

NSURL *url = [NSURL URLWithString:@"http://www.thejenkinsinstitute.com/Journal/"];
NSString *content = [NSString stringWithContentsOfURL:url];
NSString * aString = content;
NSMutableArray *substrings = [NSMutableArray new];
NSScanner *scanner = [NSScanner scannerWithString:aString];
[scanner scanUpToString:@"<p>To Download the PDF, " intoString:nil]; // Scan all characters before #
while(![scanner isAtEnd]) {
    NSString *substring = nil;
    [scanner scanString:@"<p>To Download the PDF, <a href=\"" intoString:nil]; // Scan the # character
    if([scanner scanUpToString:@"\"" intoString:&substring]) {
        // If the space immediately followed the #, this will be skipped
        [substrings addObject:substring];
    }
    [scanner scanUpToString:@"" intoString:nil]; // Scan all characters before next #
}
// do something with substrings

NSString *URLstring = [substrings objectAtIndex:0];
self.theheurl = [NSURL URLWithString:URLstring];
NSLog(@"%@", theheurl);
[substrings release];

theheurl的控制台打印输出给我一个以.pdf结尾的有效网址。

在课程中我想加载URL,我有以下内容:

- (void)viewWillAppear:(BOOL)animated
{
_appdelegate.theheurl = currentURL;
NSLog(@"%@", currentURL);
NSLog(@"%@", _appdelegate.theheurl);
[worship loadRequest:[NSURLRequest requestWithURL:currentURL cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60.0]];
timer = [NSTimer scheduledTimerWithTimeInterval:(1.0/2.0) target:self selector:@selector(tick) userInfo:nil repeats:YES];
[super viewWillAppear:YES];

}

然而,该类中的两个NSLog都返回null。我在从AppDelegate获取NSURL到类加载它时做错了什么?

2 个答案:

答案 0 :(得分:0)

第二段代码中的

只需更改分配值。

- (void)viewWillAppear:(BOOL)animated
{

AppDelegate *appdell= (AppDelegate *)[[UIApplication sharedApplication] delegate];

  currentURL=appdell.theheurl;
NSLog(@"%@", currentURL);
NSLog(@"%@", appdell.theheurl);
[worship loadRequest:[NSURLRequest requestWithURL:currentURL cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60.0]];
timer = [NSTimer scheduledTimerWithTimeInterval:(1.0/2.0) target:self selector:@selector(tick) userInfo:nil repeats:YES];
[super viewWillAppear:YES];

}

答案 1 :(得分:0)

我从您的上述内容中了解到,您需要从某个班级获取该网址,例如MyFirstViewControlle,以及;在此之后,您尝试将该网址保存在appDelegate中,例如MyAppDelegate,这样您就可以在不同的控制器中使用相同的内容,MyOtherViewController ...如果我的方向正确,那么请告诉我你如何制作object of appDelegate,它应该是这样的:(在你的MyFirstViewController中)

MyAppDelegate *objMyAppDelegate = (MyAppDelegate*)[[UIApplication sharedApplication] delegate];

并且,还要确保在appDelegate中合成url属性,如下所示:

@property(nonatomic,retain)NSURL *theURL;
@property(strong)NSURL *theURL;//ios 5.0

之后,由于您已经创建了委托对象,请执行以下操作:

objMyAppDelegate.theURL = _currentURL;

告诉我你是否还有任何疑问。