开发者

Loading text for UIButton and UITextView in background (Simple CMS)

I kinda want a CMS feature in my iPhone app. I want to load text and an image from the internet and apply them to a UIImageView, UIButton, and UITextView. However I am getting an error. Currently the code works fine with the loading of the image. I had the text code in the v开发者_Go百科iewDidAppear code however the user wasn't able to interact with the screen until the text loaded so I moved it to the loadInfo method with the Image, however it didn't like this and gave me a Bad Access error. And printed the following in the console:

2011-05-08 21:26:13.770 Fraction Calculator Lite[2184:6b03] bool _WebTryThreadLock(bool), 0x62338d0: Tried to obtain the web lock from a thread other than the main thread or the web thread. This may be a result of calling to UIKit from a secondary thread. Crashing now...

Anyone know what might be my issue?

Thanks!

This is my code:

- (void)viewDidAppear:(BOOL)animated {
    [self performSelectorInBackground:@selector(loadInfo) withObject:nil]; 
}

-(void) loadInfo {
    NSAutoreleasePool *arPool = [[NSAutoreleasePool alloc] init];

    NSError *error;
    NSString *internetTest = [NSString stringWithContentsOfURL:[NSURL URLWithString:@"http://lindahlstudios.com/cms/internettest.txt"] encoding:NSUTF8StringEncoding error:&error];
    if ([internetTest isEqualToString: @"Internet Connection Complete"]) {
        UIImage *img1 = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://lindahlstudios.com/cms/adimage.png"]]];

        [image1 setImage:img1];
        [img1 release];

        NSString *string = [NSString stringWithContentsOfURL:[NSURL URLWithString:@"http://lindahlstudios.com/cms/adtext.txt"] encoding:NSUTF8StringEncoding error:&error];
        NSString *string2 = [NSString stringWithContentsOfURL:[NSURL URLWithString:@"http://lindahlstudios.com/cms/price.txt"] encoding:NSUTF8StringEncoding error:&error];

        [adText setText:string];  //Thread 8: Program received signal: "EXC_BAD_ACCESS"
        [price setTitle:string2 forState:UIControlStateNormal];        
    }

    [arPool release];
}


You cannot invoke UIKit operations on background thread. I would suggest you get the data on background thread and then update it in the main thread.

Use blocks for ease in coding,

Once you retrieve NSData in background thread, simple assign it to the UIImage etc in the main thread via blocks,

   //get NSData from URL
   dispatch_async(dispatch_get_main_queue(), ^{
          //set  assignments for UIImage here.
   });
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜