Here is the code what I am trying..
but the thing is when I load the view first time it works.. doesn’t give any problem..
but when i try to load view again and call this code.. it gives error on arrMain addObject:
I am trying to look over it but don’t find anything..
can anyone please help??
NSUserDefaults *ds = [NSUserDefaults standardUserDefaults];
NSMutableArray *arrMain = [ds objectForKey:@"files"];
int i;
if([arrMain count] > 0)
{
i = [arrMain count] + 1;
}
else
{
arrMain = [[NSMutableArray alloc] init];
i = 1;
}
NSLog(@"File Name To Be Saved %d.txt",i);
NSArray *sd = [[NSArray alloc] init];
sd = [dict componentsSeparatedByString:@"/"];
NSMutableDictionary *dict1 = [[NSMutableDictionary alloc] init];
[dict1 setObject:[sd objectAtIndex:[sd count] - 1] forKey:@"name"];
NSString *OrgFilename = [sd objectAtIndex:[sd count] - 1];
NSArray *extArr = [[NSArray alloc] init];
extArr = [OrgFilename componentsSeparatedByString:@"."];
NSString *flExt = [extArr objectAtIndex:1];
[dict1 setObject:[NSString stringWithFormat:@"%d.txt",i,flExt] forKey:@"filename"];
// *** error happens VVVV
[arrMain addObject:dict1];
// *** error happens ^^^^
[ds setObject:arrMain forKey:@"files"];
[ds synchronize];
The problem is you are trying to retrieve a
NSMutableArrayfrom theNSUserDefaults. It will not be returning aNSMutableArray, but aNSArrayinstead. You will want to do:The reason it “worked” the first time through was
arrMainwas nil, so you created a validNSMutableArray, then saved it into theNSUserDefaults. After that, you got a valid object (non-nil), but it wasn’t the type you were expecting. Since-[NSUserDefaults objectForKey:]returns aidtype, it happily assigned it yourNSMutableArrayobject, even though it wasn’t that type.