I have a NSMutableArray which is used inside the ASIHTTPRequest process. After the data loading is done, the NSMutableArray stores the info. When I add the data as
[MyArray addObject];
I dont have any errors. However when I insert the data as
[MyArray insertObject:[UIImage imageWithData:data] atIndex:buttonTag];
I have malloc error or index out of range exception issues. I assume this as a thread safety malfunctioning. Any solution for this?
EDITED:
in appdelegate.h
@interface{
NSMutableArray *imageArray;
}
in appdelegate.m
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Override point for customization after application launch.
imageArray = [[NSMutableArray alloc] init];
return YES;
}
In the AsyncImageView.h
@interface{
AppDelegate *delegate
}
AsyncImageView.m
- (void)connectionDidFinishLoading:(NSURLConnection*)theConnection {
delegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
[delegate.imageArray insertObject:[UIImage imageWithData:data] atIndex:buttonTag];
}
It’s hard to say without seeing your code, but I doubt this is a threading issue. When you call
insertObject:atIndex:you have to be able to guarantee there are at least that many objects in the array already. Look at your code and see where you add objects, and make sure that every scenario leads to you adding enough objects thatinsertObject:atIndexwon’t fail.Hopefully this next fact is obvious to you, but just in case, I’ll point out that
initWithCapacity:does not add any elements to the array. Many people assume it does, leading to the exact problem you described.Based on your comment, the solution might be to pre-populate your array with a bunch of NSNull objects, or to use an NSDictionary instead of an array.
EDIT
Here’s a quick NSDictionary example:
Upon further review, you’ll actually need an NSMutableDictionary since you’re dynamically updating its contents. You can’t use an integer as the key, so you have to “wrap” the integer in an NSNumber object. (Note that you can use any object as a key, not just NSNumbers.)
Store an object like this:
Access it later like this:
Of course, much more information is available in Apple’s documentation or with a quick search for “NSDictionary example.”