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 NSMutableArray
from the NSUserDefaults
. It will not be returning a NSMutableArray
, but a NSArray
instead. You will want to do:
NSMutableArray *arrMain = [[[ds objectForKey:@"files"] mutableCopy] autorelease];
The reason it "worked" the first time through was arrMain
was nil, so you created a valid NSMutableArray
, then saved it into the NSUserDefaults
. After that, you got a valid object (non-nil), but it wasn't the type you were expecting. Since -[NSUserDefaults objectForKey:]
returns a id
type, it happily assigned it your NSMutableArray
object, even though it wasn't that type.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.