Using Singleton synchronized array with NSThread
Posted
by
hmthur
on Stack Overflow
See other posts from Stack Overflow
or by hmthur
Published on 2011-02-27T12:36:37Z
Indexed on
2011/02/27
15:25 UTC
Read the original article
Hit count: 271
I have a books app with a UISearchBar, where the user types any book name and gets search results (from ext API call) below as he types.
I am using a singleton variable in my app called retrievedArray which stores all the books.
@interface Shared : NSObject {
NSMutableArray *books;
}
@property (nonatomic, retain) NSMutableArray *books;
+ (id)sharedManager;
@end
This is accessed in multiple .m files using NSMutableArray *retrievedArray; ...in the header file
retrievedArray = [[Shared sharedManager] books];
My question is how do I ensure that the values inside retrievedArray remain synchronized across all the classes.
Actually the values inside retrievedArray gets added through an NSXMLParser (i.e. through external web service API). There is a separate XMLParser.m file, where I do all the parsing and fill the array. The parsing is done on a separate thread.
- (void) run: (id) param {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSXMLParser *parser = [[NSXMLParser alloc] initWithContentsOfURL: [self URL]];
[parser setDelegate: self];
[parser parse];
[parser release];
NSString *tmpURLStr = [[self URL]absoluteString];
NSRange range_srch_book = [tmpURLStr rangeOfString:@"v1/books"];
if (range_srch_book.location != NSNotFound)
[delegate performSelectorOnMainThread:@selector(parseDidComplete_srch_book) withObject:nil waitUntilDone:YES];
[pool release];
}
- (void) parseXMLFile: (NSURL *) url
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
[self setURL: url];
NSThread* myThread = [[NSThread alloc] initWithTarget:self
selector:@selector(run:)
object: nil];
[retrievedArray removeAllObjects];
[myThread start];
[pool release];
}
There seems to be some synchronization issues if the user types very quickly (It seems to be working fine if the user types slowly)....So there are 2 views in which the content of an object in this shared array item is displayed; List and Detail. If user types fast and clicks on A in List view, he is shown B in detail view...That is the main issue.
I have tried literally all the solutions I could think of, but am still unable to fix the issue. Please suggest some suitable fixes.
© Stack Overflow or respective owner