开发者

iPhone - Threading and Delegation

I'm running some code in a background thread to get a text file from a service.开发者_运维技巧 That code fires a delegate at some point. It throws as SIGABRT error once the delegate is being called and well, my concept doesn't sound convincing to me either.

The code running at the background thread:

- (void)FetchStores
{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; 

    // Fetch from service
    NSString *serviceURL = @"http://../index.html";
    NSURL *myURL = [NSURL URLWithString:serviceURL];
    NSData *dataRep = [NSData dataWithContentsOfURL:myURL];

    storesList = [[Stores alloc] init];
    storesList.storesDelegate = self;
    [storesList FetchWithNSData:dataRep];

    [pool release];
}

The storesList object will fire a delegate once all the stores have been extracted from the service. The delegate is getting caught by a function at the main thread.

Do you have any suggestions what am I doing wrong ?

Thank you,

f.


When calling the delegate, somewhere, you should make the switch to the main thread. Especially if somewhere, you are updating the UI based on the data fetched.

You can use - (void)performSelectorOnMainThread:(SEL)aSelector withObject:(id)arg waitUntilDone:(BOOL)wait to make the switch.

Maybe like this:

storesList = [[Stores alloc] init];
storesList.storesDelegate = self;
[storesList performSelectorOnMainThread:@selector(FetchWithNSData:) withObject:dataRep waitUntilDone:TRUE];

In your case, you should use waitUntilDone:TRUE so that the FetchWithNSData method gets a chance to retain the data.


It seems quite likely that FetchWithNSData: does not retain the passed dataRep and the data gets deallocated on the next line where you drain the local autorelease pool?

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜