showing elements of dictionary - objective-c

I have a plist file that contains array of dictionaries, and I'm trying to show in console the elements of the dictionnaries... here is my code:
NSString *path = [[NSBundle mainBundle] pathForResource:#"validrep" ofType:#"plist"];
descArray = [[NSMutableArray alloc] init];
NSString *key = [NSString stringWithFormat:#"test %i",i+1];
NSMutableArray *tabreponses = [[NSMutableArray arrayWithContentsOfFile:path] retain];
NSDictionary *dictreponses = [NSDictionary dictionaryWithObject:[tabreponses objectAtIndex:i] forKey:key];
[descArray addObject:dictreponses];
NSDictionary *dictionary = [descArray objectAtIndex:i];
NSArray *array = [dictionary objectForKey:key];
NSLog(#"the array is %#, it contains %i elements.",array,[array count]);
Till now everythig is working correctly and this is what the console is showing:
2011-12-14 14:52:33.845 Daltonien[1459:b603] the array is {
rep1 = "1 \U00e9toile derri\U00e8re un quadrillage ";
rep2 = "1 lettre B derri\U00e8re un quadrillage";
rep3 = "1 quadrillage seul ";
}, it contains 3 elements.
but it doesn't work when i try to show the first element of the array, i do it like this:
NSLog(#"the array is %#, it contains %i elements, the first element is %# .",array,[array count],[array objectAtIndex:i]);
This results in an exception:
Daltonien[1478:b603] -[__NSCFDictionary objectAtIndex:]:
unrecognized selector sent to instance 0x4b8cbd0
Daltonien[1478:b603] *** Terminating app due to
uncaught exception 'NSInvalidArgumentException',
reason: '-[__NSCFDictionary objectAtIndex:]:
unrecognized selector sent to instance 0x4b8cbd0'
*** Call stack at first throw:
(
0 CoreFoundation 0x00dca5a9 __exceptionPreprocess + 185
1 libobjc.A.dylib 0x00f1e313 objc_exception_throw + 44
2 CoreFoundation 0x00dcc0bb -[NSObject(NSObject) doesNotRecognizeSelector:] + 187
3 CoreFoundation 0x00d3b966 ___forwarding___ + 966
4 CoreFoundation 0x00d3b522 _CF_forwarding_prep_0 + 50
5 Daltonien 0x00002cff -[DetailViewController tableView:numberOfRowsInSection:] + 193
6 UIKit 0x004772b7 -[UISectionRowData refreshWithSection:tableView:tableViewRowData:] + 1834
7 UIKit 0x00474d88 -[UITableViewRowData numberOfRows] + 108
8 UIKit 0x00328677 -[UITableView noteNumberOfRowsChanged] + 132
9 UIKit 0x00335708 -[UITableView reloadData] + 773
10 UIKit 0x00332844 -[UITableView layoutSubviews] + 42
11 QuartzCore 0x01d6aa5a -[CALayer layoutSublayers] + 181
12 QuartzCore 0x01d6cddc CALayerLayoutIfNeeded + 220
13 QuartzCore 0x01d120b4 _ZN2CA7Context18commit_transactionEPNS_11TransactionE + 310
14 QuartzCore 0x01d13294 _ZN2CA11Transaction6commitEv + 292
15 QuartzCore 0x01d1346d _ZN2CA11Transaction17observer_callbackEP19__CFRunLoopObservermPv + 99
16 CoreFoundation 0x00dab89b __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 27
17 CoreFoundation 0x00d406e7 __CFRunLoopDoObservers + 295
18 CoreFoundation 0x00d091d7 __CFRunLoopRun + 1575
19 CoreFoundation 0x00d08840 CFRunLoopRunSpecific + 208
20 CoreFoundation 0x00d08761 CFRunLoopRunInMode + 97
21 GraphicsServices 0x017211c4 GSEventRunModal + 217
22 GraphicsServices 0x01721289 GSEventRun + 115
23 UIKit 0x002c8c93 UIApplicationMain + 1160
24 Daltonien 0x000020c8 main + 102
25 Daltonien 0x00002059 start + 53
26 ??? 0x00000001 0x0 + 1
)
terminate called throwing an exception
with what should i change objectAtIndex:i
THANX for helping me.

The problem is this:
Your key, #"test1", is actually a dictionary, not an array...
To get the first key / value of the dictionary, you would do the following
[[myDictionary keys] objectAtIndex:0]
[[myDictionary values] objectAtIndex:0]

If you want the first object in your array, you'll want something like this:
[array objectAtIndex:0];
To loop through all of the objects, this will do it:
for (id someObject in array) {
// Do stuff
}

Related

Data-core NSException

I don't know where is my problem because the entity "Utente" exist.
Error code:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '+entityForName: nil is not a legal NSManagedObjectContext parameter searching for entity name 'Utente''
*** First throw call stack:
(
0 CoreFoundation 0x0000000101bf0495 __exceptionPreprocess + 165
1 libobjc.A.dylib 0x00000001016f099e objc_exception_throw + 43
2 CoreData 0x0000000101e76599 +[NSEntityDescription entityForName:inManagedObjectContext:] + 217
3 CoreData 0x0000000101eb2e7e +[NSEntityDescription insertNewObjectForEntityForName:inManagedObjectContext:] + 30
4 VucmpraJson 0x000000010000514b -[LoginViewController login:] + 4843
5 UIKit 0x000000010029ef06 -[UIApplication sendAction:to:from:forEvent:] + 80
6 UIKit 0x000000010029eeb4 -[UIApplication sendAction:toTarget:fromSender:forEvent:] + 17
7 UIKit 0x000000010037b880 -[UIControl _sendActionsForEvents:withEvent:] + 203
8 UIKit 0x000000010037adc0 -[UIControl touchesEnded:withEvent:] + 530
9 UIKit 0x00000001002d5d05 -[UIWindow _sendTouchesForEvent:] + 701
10 UIKit 0x00000001002d66e4 -[UIWindow sendEvent:] + 925
11 UIKit 0x00000001002ae29a -[UIApplication sendEvent:] + 211
12 UIKit 0x000000010029baed _UIApplicationHandleEventQueue + 9579
13 CoreFoundation 0x0000000101b7fd21 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17
14 CoreFoundation 0x0000000101b7f5f2 __CFRunLoopDoSources0 + 242
15 CoreFoundation 0x0000000101b9b46f __CFRunLoopRun + 767
16 CoreFoundation 0x0000000101b9ad83 CFRunLoopRunSpecific + 467
17 GraphicsServices 0x00000001040d0f04 GSEventRunModal + 161
18 UIKit 0x000000010029de33 UIApplicationMain + 1010
19 VucmpraJson 0x0000000100021d13 main + 115
20 libdyld.dylib 0x00000001025f15fd start + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
Code:
#property (nonatomic,strong) NSManagedObjectContext* managedObjectContext;
.
.
.
NSManagedObjectContext *context = [self managedObjectContext];
NSManagedObject * Utente = [NSEntityDescription insertNewObjectForEntityForName:#"Utente" inManagedObjectContext:context];
[Utente setValue: emailText.text forKey:#"email"];
NSError *error;
//[context save:&error];
if (![context save:&error]) {
NSLog(#"Whoops, couldn't save: %#", [error localizedDescription]);
}
entities: Utente
attributes: email;password
thx to much guys
nil is not a legal NSManagedObjectContext parameter searching for entity name 'Utente'
means that your managed object context is nil. Check self.managedObjectContext assignment.
edit
if (! [self managedObjectContext]) {
NSLog(#"You will receive your exception");
} else {
// Insert new entity into specified context
}

How to understand this crash?

Crash report:
0 ??? 0x0 + 0
1 TestPrj -[AppListReader addInstalledApps:] (AppListReader.m:186) + 77516
2 TestPrj -[AppListReader getAppsInstalled] (AppListReader.m:161) + 77320
3 TestPrj -[DetectAppsInstalledService activate:] (DetectAppsInstalledService.m:48) + 197612
4 TestPrj -[BusinessManager handleBG] (BusinessManager.m:762) + 116672
5 TestPrj -[BusinessManager activate:] (BusinessManager.m:208) + 106236
6 TestPrj -[AppDelegate launchViewController:] (AppDelegate.m:338) + 32564
7 TestPrj -[AppDelegate application:didFinishLaunchingWithOptions:] (AppDelegate.m:153) + 27396
8 UIKit <redacted> + 316
9 UIKit <redacted> + 1564
10 UIKit <redacted> + 772
11 UIKit <redacted> + 3316
12 UIKit <redacted> + 104
13 UIKit <redacted> + 672
14 GraphicsServices <redacted> + 676
15 GraphicsServices <redacted> + 48
16 CoreFoundation <redacted> + 56
17 CoreFoundation <redacted> + 444
18 CoreFoundation <redacted> + 1620
19 CoreFoundation CFRunLoopRunSpecific + 452
20 UIKit <redacted> + 784
21 UIKit UIApplicationMain + 1156
22 TestPrj main (main.m:21) + 23548
23 libdyld.dylib <redacted> + 4
Line 186 is:
NSMutableArray *allObjetcsArr = [self getInstalled];
This is implementation:
-(NSMutableArray *)getInstalled
{
NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:#"ApplicationType",#"Any", [self defaultReturnAttributes] ,#"ReturnAttributes",nil];
MobileInstallationLookup = dlsym(RTLD_DEFAULT, "MobileInstallationLookup");
NSDictionary *apps = (__bridge NSDictionary *)((__bridge void*)MobileInstallationLookup(options));
NSMutableArray *allObjetcsArr = [[NSMutableArray alloc]initWithArray:[apps allValues]];
return allObjetcsArr;
}
Crash is received via BugSense and I am not able to reproduce it. I think it is related to MobileInstallationLookup framework (which is private api) but I am not sure.
It is not clear for me, why
-(NSMutableArray *)getInstalled
Is not present in stack trace, only ??? 0x0 + 0
My money is on these lines:
MobileInstallationLookup = dlsym(RTLD_DEFAULT, "MobileInstallationLookup");
NSDictionary *apps = (__bridge NSDictionary *)((__bridge void*)MobileInstallationLookup(options));
MobileInstallationLookup is obviously a global, but it's not clear why; for example if it's global they why is it being re-assigned in this method and why does the variable start with a capital letter (which is unconventional)?
There is no check to ensure that dlsym() succeeded, and dereferencing a null pointer would cause the crash you are getting.

*** Assertion failure in -[AppDelegate createDatabaseExecutableFile]

I have application and in application delegate i have code for copy the db file into document folder but it's not working i don't know why because it was working before, and giving following error, please take a look and hope you can find something. Thanks
// Creates a writable copy of the bundled default database in the application Documents directory.
- (void) createDatabaseExecutableFile {
// First, test for existence.
BOOL _successDB;
BOOL _successConfig;
NSFileManager* _fileManager = [NSFileManager defaultManager];
NSError* _error;
NSArray* _paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString* _documentsDirectory = [_paths objectAtIndex:0];
NSString* _writableDBPath = [_documentsDirectory stringByAppendingPathComponent:#"turfnutritiontool_ver.db"];
NSString* _writableConfigPath = [_documentsDirectory stringByAppendingPathComponent:#"Configuration.plist"];
_successDB = [_fileManager fileExistsAtPath:_writableDBPath];
_successConfig = [_fileManager fileExistsAtPath:_writableConfigPath];
if (_successDB && _successConfig) {
return;
}
// The writable database does not exist, so copy the default to the appropriate location.
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"turfnutritiontool_ver.db"];
NSString *defaultConfigPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"Configuration.plist"];
_successDB = [_fileManager copyItemAtPath:defaultDBPath toPath:_writableDBPath error:&_error];
_successConfig = [_fileManager copyItemAtPath:defaultConfigPath toPath:_writableConfigPath error:&_error];
if (!_successDB || !_successConfig) {
NSAssert1(0, #"Failed to create writable database file with message '%#'.", [_error localizedDescription]);
}
}
This is the error:
2012-04-02 13:52:01.162 TurfNutritionTool_ver_5.1[2379:b903] *** Assertion failure in -[AppDelegate createDatabaseExecutableFile], /Development/TurfNutritionTool_IOS_5.1/TurfNutritionTool/AppDelegate.m:188
2012-04-02 13:52:01.165 TurfNutritionTool_ver_5.1[2379:b903] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Failed to create writable database file with message 'The operation couldn’t be completed. File exists'.'
*** Call stack at first throw:
(
0 CoreFoundation 0x0179a5a9 __exceptionPreprocess + 185
1 libobjc.A.dylib 0x018ee313 objc_exception_throw + 44
2 CoreFoundation 0x01752ef8 +[NSException raise:format:arguments:] + 136
3 Foundation 0x011fc3bb -[NSAssertionHandler handleFailureInMethod:object:file:lineNumber:description:] + 116
4 TurfNutritionTool_ver_5.1 0x00003fef -[AppDelegate createDatabaseExecutableFile] + 831
5 TurfNutritionTool_ver_5.1 0x00003486 -[AppDelegate application:didFinishLaunchingWithOptions:] + 86
6 UIKit 0x009f9c89 -[UIApplication _callInitializationDelegatesForURL:payload:suspended:] + 1163
7 UIKit 0x009fbd88 -[UIApplication _runWithURL:payload:launchOrientation:statusBarStyle:statusBarHidden:] + 439
8 UIKit 0x00a06617 -[UIApplication handleEvent:withNewEvent:] + 1533
9 UIKit 0x009feabf -[UIApplication sendEvent:] + 71
10 UIKit 0x00a03f2e _UIApplicationHandleEvent + 7576
11 GraphicsServices 0x01e21992 PurpleEventCallback + 1550
12 CoreFoundation 0x0177b944 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__ + 52
13 CoreFoundation 0x016dbcf7 __CFRunLoopDoSource1 + 215
14 CoreFoundation 0x016d8f83 __CFRunLoopRun + 979
15 CoreFoundation 0x016d8840 CFRunLoopRunSpecific + 208
16 CoreFoundation 0x016d8761 CFRunLoopRunInMode + 97
17 UIKit 0x009fb7d2 -[UIApplication _run] + 623
18 UIKit 0x00a07c93 UIApplicationMain + 1160
19 TurfNutritionTool_ver_5.1 0x00002ddd main + 125
20 TurfNutritionTool_ver_5.1 0x00002d55 start + 53
21 ??? 0x00000001 0x0 + 1
)
terminate called throwing an exception(lldb)
It says "file exists". Isn't that enough of a clue?
From the NSFileManager docs:
If a file with the same name already exists at dstPath, this method aborts the copy attempt and returns an appropriate error.
By the way, you should check the error after each copy, not once at the end because if an error occurs on the first copy, and the second copy, you'll lose the error information from the first copy.

SIGABRT while adding objects to an NSMutableArray

I have a method which returns an NSArray with points to be plotted. Following is the code for my method.
- (NSArray *)pointsToPlot:(GraphView *)requester
{
NSMutableArray *points = [[NSSet alloc] init];
CGPoint midPoint;
midPoint.x = self.graph.bounds.origin.x + self.graph.bounds.size.width / 2;
midPoint.y = self.graph.bounds.origin.y + self.graph.bounds.size.height / 2;
//Find points to plot
NSValue *point1 = [NSValue valueWithCGPoint:CGPointMake(midPoint.x - 10, midPoint.y)];
NSValue *point2 = [NSValue valueWithCGPoint:CGPointMake(midPoint.x, midPoint.y - 10)];
NSValue *point3 = [NSValue valueWithCGPoint:CGPointMake(midPoint.x + 10, midPoint.y)];
[points addObject:point1];
[points addObject:point2];
[points addObject:point3];
[points autorelease];
return points;
}
I am getting SIGABRT as soon as I add point1 to the points array.
Following is the stack trace obtained:
2011-10-27 10:43:36.939 Graphing Calculator[7056:207] -[__NSSet0 addObject:]: unrecognized selector sent to instance 0x4b57900
2011-10-27 10:43:36.943 Graphing Calculator[7056:207] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSSet0 addObject:]: unrecognized selector sent to instance 0x4b57900'
*** Call stack at first throw:
(
0 CoreFoundation 0x00dc95a9 __exceptionPreprocess + 185
1 libobjc.A.dylib 0x00f1d313 objc_exception_throw + 44
2 CoreFoundation 0x00dcb0bb -[NSObject(NSObject) doesNotRecognizeSelector:] + 187
3 CoreFoundation 0x00d3a966 ___forwarding___ + 966
4 CoreFoundation 0x00d3a522 _CF_forwarding_prep_0 + 50
5 Graphing Calculator 0x000073cd -[GraphViewController pointsToPlot:] + 1037
6 Graphing Calculator 0x00006895 -[GraphView drawRect:] + 965
7 UIKit 0x00053187 -[UIView(CALayerDelegate) drawLayer:inContext:] + 426
8 QuartzCore 0x016b3b5e -[CALayer drawInContext:] + 143
9 QuartzCore 0x016bfe47 _ZL16backing_callbackP9CGContextPv + 85
10 QuartzCore 0x0160d1f7 CABackingStoreUpdate + 2246
11 QuartzCore 0x016bfd24 -[CALayer _display] + 1085
12 QuartzCore 0x016b627d CALayerDisplayIfNeeded + 231
13 QuartzCore 0x0165b0c3 _ZN2CA7Context18commit_transactionEPNS_11TransactionE + 325
14 QuartzCore 0x0165c294 _ZN2CA11Transaction6commitEv + 292
15 QuartzCore 0x0165c46d _ZN2CA11Transaction17observer_callbackEP19__CFRunLoopObservermPv + 99
16 CoreFoundation 0x00daa89b __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 27
17 CoreFoundation 0x00d3f6e7 __CFRunLoopDoObservers + 295
18 CoreFoundation 0x00d081d7 __CFRunLoopRun + 1575
19 CoreFoundation 0x00d07840 CFRunLoopRunSpecific + 208
20 CoreFoundation 0x00d07761 CFRunLoopRunInMode + 97
21 GraphicsServices 0x010011c4 GSEventRunModal + 217
22 GraphicsServices 0x01001289 GSEventRun + 115
23 UIKit 0x00029c93 UIApplicationMain + 1160
24 Graphing Calculator 0x000021d9 main + 121
25 Graphing Calculator 0x00002155 start + 53
)
terminate called after throwing an instance of 'NSException'
Could someone please explain me what am I doing wrong here?
Change
NSMutableArray *points = [[NSSet alloc] init];
to
NSMutableArray *points = [[NSMutableArray alloc] init];
You are creating and initializing an NSSet and storing it to a reference for NSMutableArray.
Change the following line:
NSMutableArray *points = [[NSSet alloc] init];
To this line:
NSMutableArray *points = [[NSMutableArray alloc] initWithCapacity:3];

NSMutableArray adding/removing objects + NSUserDefaults

I want to make a "Favorites" in my RSS reader. My RSS parser is parsing a RSS feed to NSMutableArray, and then object "item" is created from part of my rss (selected post).
My code:
//Creating mutable array and adding items:
- (void)viewDidLoad {
if (favoritedAlready == nil) {
favoritedAlready = [[NSMutableArray alloc] init];
[[NSUserDefaults standardUserDefaults] setObject:favoritedAlready forKey:#"favorites"];
[[NSUserDefaults standardUserDefaults] synchronize];
NSLog(#"избранное с нуля");
}
}
- (void) addToFavorites {
NSMutableArray* favoritedAlready = [[NSUserDefaults standardUserDefaults] objectForKey:#"favorites"];
[favoritedAlready addObject: item];
[[NSUserDefaults standardUserDefaults] setObject:favoritedAlready forKey:#"favorites"];
[[NSUserDefaults standardUserDefaults] synchronize];
NSLog(#"Добавлено в избранное. В избранном %i статей", [favoritedAlready count]);
}
//Removing items (another View)
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
rssItems = [[NSUserDefaults standardUserDefaults] objectForKey:#"favorites"];
[self.tableView reloadData];
NSLog(#"Загрузилось избранное, %i избранных статей", [rssItems count]);
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
NSLog(#"Номерок строчки в которой удаляемый объект %i", indexPath.row+1);
[rssItems removeObjectAtIndex:indexPath.row];
[self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
[[NSUserDefaults standardUserDefaults] setObject:rssItems forKey:#"favorites"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
It worked perfectly initially, but when I added and removed items, it started crashing.
Crash logs:
I added object to Favorites and removed it:
2011-09-25 20:14:44.534 ARSSReader[36211:11303] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '-[__NSCFArray removeObjectAtIndex:]: mutating method sent to immutable object'
*** Call stack at first throw:
(
0 CoreFoundation 0x015505a9 __exceptionPreprocess + 185
1 libobjc.A.dylib 0x016a4313 objc_exception_throw + 44
2 CoreFoundation 0x01508ef8 +[NSException raise:format:arguments:] + 136
3 CoreFoundation 0x01508e6a +[NSException raise:format:] + 58
4 CoreFoundation 0x01547dd1 -[__NSCFArray removeObjectAtIndex:] + 193
5 ARSSReader 0x000a0ced -[FavoritesView tableView:commitEditingStyle:forRowAtIndexPath:] + 173
6 UIKit 0x00876037 -[UITableView(UITableViewInternal) animateDeletionOfRowWithCell:] + 101
7 UIKit 0x0080b4fd -[UIApplication sendAction:to:from:forEvent:] + 119
8 UIKit 0x0089b799 -[UIControl sendAction:to:forEvent:] + 67
9 UIKit 0x0089dc2b -[UIControl(Internal) _sendActionsForEvents:withEvent:] + 527
10 UIKit 0x0089c7d8 -[UIControl touchesEnded:withEvent:] + 458
11 UIKit 0x0082fded -[UIWindow _sendTouchesForEvent:] + 567
12 UIKit 0x00810c37 -[UIApplication sendEvent:] + 447
13 UIKit 0x00815f2e _UIApplicationHandleEvent + 7576
14 GraphicsServices 0x01c91992 PurpleEventCallback + 1550
15 CoreFoundation 0x01531944 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__ + 52
16 CoreFoundation 0x01491cf7 __CFRunLoopDoSource1 + 215
17 CoreFoundation 0x0148ef83 __CFRunLoopRun + 979
18 CoreFoundation 0x0148e840 CFRunLoopRunSpecific + 208
19 CoreFoundation 0x0148e761 CFRunLoopRunInMode + 97
20 GraphicsServices 0x01c901c4 GSEventRunModal + 217
21 GraphicsServices 0x01c90289 GSEventRun + 115
22 UIKit 0x00819c93 UIApplicationMain + 1160
23 ARSSReader 0x00001e79 main + 121
24 ARSSReader 0x00001df5 start + 53
)
terminate called throwing an exception(gdb)
But, if I added item, restarted app and then removed it, it worked perfectly.
I added item, restarted app, removed item, and tried to add new item:
2011-09-25 20:19:19.212 ARSSReader[36461:11303] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '-[__NSCFArray insertObject:atIndex:]: mutating method sent to immutable object'
*** Call stack at first throw:
(
0 CoreFoundation 0x015505a9 __exceptionPreprocess + 185
1 libobjc.A.dylib 0x016a4313 objc_exception_throw + 44
2 CoreFoundation 0x01508ef8 +[NSException raise:format:arguments:] + 136
3 CoreFoundation 0x01508e6a +[NSException raise:format:] + 58
4 CoreFoundation 0x01547cf1 -[__NSCFArray insertObject:atIndex:] + 209
5 CoreFoundation 0x01544c14 -[__NSCFArray addObject:] + 68
6 ARSSReader 0x00004b35 -[DetailsViewController addToFavorites] + 149
7 UIKit 0x0080b4fd -[UIApplication sendAction:to:from:forEvent:] + 119
8 UIKit 0x00a1dcc3 -[UIBarButtonItem(UIInternal) _sendAction:withEvent:] + 156
9 UIKit 0x0080b4fd -[UIApplication sendAction:to:from:forEvent:] + 119
10 UIKit 0x0089b799 -[UIControl sendAction:to:forEvent:] + 67
11 UIKit 0x0089dc2b -[UIControl(Internal) _sendActionsForEvents:withEvent:] + 527
12 UIKit 0x0089c7d8 -[UIControl touchesEnded:withEvent:] + 458
13 UIKit 0x0082fded -[UIWindow _sendTouchesForEvent:] + 567
14 UIKit 0x00810c37 -[UIApplication sendEvent:] + 447
15 UIKit 0x00815f2e _UIApplicationHandleEvent + 7576
16 GraphicsServices 0x01c91992 PurpleEventCallback + 1550
17 CoreFoundation 0x01531944 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__ + 52
18 CoreFoundation 0x01491cf7 __CFRunLoopDoSource1 + 215
19 CoreFoundation 0x0148ef83 __CFRunLoopRun + 979
20 CoreFoundation 0x0148e840 CFRunLoopRunSpecific + 208
21 CoreFoundation 0x0148e761 CFRunLoopRunInMode + 97
22 GraphicsServices 0x01c901c4 GSEventRunModal + 217
23 GraphicsServices 0x01c90289 GSEventRun + 115
24 UIKit 0x00819c93 UIApplicationMain + 1160
25 ARSSReader 0x00001e79 main + 121
26 ARSSReader 0x00001df5 start + 53
)
terminate called throwing an exception(gdb)
In addToFavorites
NSMutableArray* favoritedAlready = [[NSUserDefaults standardUserDefaults] objectForKey:#"favorites"];
will return an NSArray (it makes no difference it you save a mutable version), not an NSMutableArray
You need to create a mutable version:
NSMutableArray* favoritedAlready = [[[NSUserDefaults standardUserDefaults] objectForKey:#"favorites"] mutableCopy];
You can obviously not add items to a non-mutable array. Also just casting the return value to a NSMutableArray is wrong, it may work or it may not but that is irrelevant.
The issue is that NSUserDefaults only returns immutable arrays, even if you put in a mutable array:
Special Considerations:
The returned array and its contents are immutable, even if the values you originally set were mutable.
Therefore, when you fetch your array from NSUserDefaults, you'll have to convert it by using the mutable copy method, or by creating a new NSMutableArray using the returned NSArray.
You may want to consolidate changes to fewer method calls to NSUserDefaults—perhaps in batches, perhaps at certain time intervals. Have a local array keep track of changes, then write the changes out, rather than grabbing the array from NSUserDefaults first. This will save one more trip to disk and will make your code more efficient as well.