UITableView Alphabetizing - objective-c

I have a UITableView that is successfully populated from a database, put into a NSArray and every cell is clickable and performs the correct action when selected, however the list is out of alphabetical order. In order to sort them into alphabetical order, I use the following code:
NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:#"Name" ascending:YES];
sortedArray = [buildings sortedArrayUsingDescriptors:[NSArray arrayWithObject:sort]];
The alphabetizing works correctly, however when some of the cells (in this example it was the first cell in the list) are clicked the app terminates with an uncaught exception:
'NSRangeException' '*** -[__NSArrayM objectAtIndex:]: index 1 beyond bounds [0 .. 0]'
I'd be happy to post more code excerpts, I am just unsure of what relevant information would be needed to help answer this question.
Edit:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSInteger r = [indexPath row];
[tableView deselectRowAtIndexPath:indexPath animated:YES];
if(infoInst != nil) {
infoInst = nil;
}
infoInst = [[DirInfoListing alloc] initWithNibName:#"DirInfoListing" bundle:nil building:[self.listData objectAtIndex:r] map:mapUI];
NSLog(#"infoInst building: %#", [self.listData objectAtIndex:r]);
NSString *deviceType = [UIDevice currentDevice].model;
if([deviceType isEqualToString:#"iPad"] || [deviceType isEqualToString:#"iPad Simulator"]){
[self presentModalViewController:infoInst animated:YES];
} else {
[self.navigationController pushViewController:infoInst animated:YES];
}
}
Edit: Here is the stack trace immediately before the error is thrown
2013-07-03 16:56:56.579 thestanforddaily[32907:1a303] Stack trace : (
0 thestanforddaily 0x002190d9 -[Directory tableView:didSelectRowAtIndexPath:] + 457
1 UIKit 0x01ae871d -[UITableView _selectRowAtIndexPath:animated:scrollPosition:notifyDelegate:] + 1164
2 UIKit 0x01ae8952 -[UITableView _userSelectRowAtPendingSelectionIndexPath:] + 201
3 Foundation 0x0237086d __NSFireDelayedPerform + 389
4 CoreFoundation 0x02acd966 __CFRUNLOOP_IS_CALLING_OUT_TO_A_TIMER_CALLBACK_FUNCTION__ + 22
5 CoreFoundation 0x02acd407 __CFRunLoopDoTimer + 551
6 CoreFoundation 0x02a307c0 __CFRunLoopRun + 1888
7 CoreFoundation 0x02a2fdb4 CFRunLoopRunSpecific + 212
8 CoreFoundation 0x02a2fccb CFRunLoopRunInMode + 123
9 GraphicsServices 0x0327b879 GSEventRunModal + 207
10 GraphicsServices 0x0327b93e GSEventRun + 114
11 UIKit 0x01a58a9b UIApplicationMain + 1175
12 thestanforddaily 0x00002f4d main + 141
13 thestanforddaily 0x00002e75 start + 53
)
2013-07-03 16:57:13.740 thestanforddaily[32907:1a303] *** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayM objectAtIndex:]: index 1 beyond bounds [0 .. 0]'
*** First throw call stack:
(0x2af9052 0x28e8d0a 0x2ae5db8 0x21cb0e 0x1b1e64e 0x1b1e941 0x1b3047d 0x1b3066f 0x1b3093b 0x1b313df 0x1b31986 0x1b315a4 0x219250 0x1ae871d 0x1ae8952 0x237086d 0x2acd966 0x2acd407 0x2a307c0 0x2a2fdb4 0x2a2fccb 0x327b879 0x327b93e 0x1a58a9b 0x2f4d 0x2e75)
Thank you!

The only array access I see in didSelectRowAtIndexPath is [self.listData objectAtIndex:r]. So it would seem your listData array isn't in sync with the table's data model. From the code you posted, the array sortedArray should correspond to the data model, so make sure listData and sortedArray are kept in sync or just have one array. If you still can't figure it out, please post your UITableViewDataSource methods as well as the methods where you set up your various array variables.

NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:#"Name" ascending:YES];
sortedArray = [buildings count] <= 1 ? buildings : [buildings sortedArrayUsingDescriptors:[NSArray arrayWithObject:sort]];
Unless you require sortedArray to be a different instance than buildings. Then you should change the statement accordingly.

Related

HOWTO: Sort TableView per column using NSSortDescriptor when column names are unknown?

I'm loading a CSV file that I know nothing about except that the first row are column headers, which could be anything. The number of columns is unknown too. I tried to add a sortDescriptorPrototype to each column and when I do I get up/down arrows visible in the TableView.
for(NSTableColumn * col in self.tableView.tableColumns){
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey: col.title ascending: YES];
col.sortDescriptorPrototype = sortDescriptor;
}
Each time I click on the column sortDescriptorsDidChange is called:
- (void)tableView:(NSTableView *)tableView sortDescriptorsDidChange:(NSArray *)oldDescriptors
{
[_data sortUsingDescriptors: [tableView sortDescriptors]];
[tableView reloadData];
}
_data is a NSMutableArray where data is stored and first row are the header names. Each row is another NSArray Unfortunately I get this error:
2017-04-17 12:35:09.979142+0200 Table Tool[20954:2577488] [General] [<__NSCFString 0x610000474840> valueForUndefinedKey:]: this class is not key value coding-compliant for the key beds.
2017-04-17 12:35:09.982161+0200 Table Tool[20954:2577488] [General] (
0 CoreFoundation 0x00007fffb31a837b __exceptionPreprocess + 171
1 libobjc.A.dylib 0x00007fffc7f9c48d objc_exception_throw + 48
2 CoreFoundation 0x00007fffb31a82c9 -[NSException raise] + 9
3 Foundation 0x00007fffb4c83e5e -[NSObject(NSKeyValueCoding) valueForUndefinedKey:] + 226
4 Foundation 0x00007fffb4b55d9c -[NSObject(NSKeyValueCoding) valueForKey:] + 283
5 Foundation 0x00007fffb4b59aac -[NSArray(NSKeyValueCoding) valueForKey:] + 467
6 Foundation 0x00007fffb4b55b79 -[NSArray(NSKeyValueCoding) valueForKeyPath:] + 448
7 Foundation 0x00007fffb4b7cc9f _sortedObjectsUsingDescriptors + 371
8 Foundation 0x00007fffb4be94f7 -[NSMutableArray(NSKeyValueSorting) sortUsingDescriptors:] + 468
9 Table Tool 0x00000001000051d8 -[Document tableView:sortDescriptorsDidChange:] + 184
10 AppKit 0x00007fffb0f05425 -[NSTableView setSortDescriptors:] + 260
11 AppKit 0x00007fffb13c9fbc -[NSTableView _changeSortDescriptorsForClickOnColumn:] + 480
Obviously I have read a lot on the topic, but all examples assume that you know column names at design-time. I'm interested in a solution with NSSortDescriptor and sortUsingDescriptors in Obj-C or Swift, some explanation on sortDescriptorPrototype and why you need it in the first place, since sortDescriptor changes when I click on the column. Is there anything in KVC I can use for the sorting key, like "self" (there is ...valueForKeyPath:#"#sum.self"...)?
Some useful links:
https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/TableView/SortingTableViews/SortingTableViews.html
https://www.raywenderlich.com/143828/macos-nstableview-tutorial
Here is a completely moronic way of solving it that partly works:
First I extract the column index with this method:
-(NSUInteger)getColumnIndexFromTableViewSortDescriptor {
for(NSUInteger i = 0; i < _maxColumnNumber; i++){
if(_tableView.tableColumns[i].title == _tableView.sortDescriptors[0].key){
return i;
}
}
assert(false && "Missing column name");
return 0;
}
Then I sort the array in-place with sortUsingComparator. Surely this has to be the "wrong". It's completely idiotic to use sortDescriptors if they are not used, other than to figuring out which column was clicked. I guess the click event could figure that out too?
-(void)tableView:(NSTableView *)tableView sortDescriptorsDidChange: (NSArray *)oldDescriptors
{
NSUInteger idx = self.getColumnIndexFromTableViewSortDescriptor;
if(tableView.sortDescriptors[0].ascending){
[_data sortUsingComparator: ^(id obj1, id obj2) {
return [[obj2 objectAtIndex:idx] compare:[obj1 objectAtIndex:idx]];
}];
} else {
[_data sortUsingComparator: ^(id obj1, id obj2) {
return [[obj1 objectAtIndex:idx] compare:[obj2 objectAtIndex:idx]];
}];
}
[tableView reloadData];
}
Now the CSV data I'm importing the data in the columns is not uniform, so it could be a NSNumber, followed by three NSDecimalNumber and a few NSString. Partly that's a problem with the data and/or the CSV parser I'm using (ripped from the web, but I will rewrite the sucker later).
So you could end up comparing NSDecimalNumber with NSString which will generate errors like:
unrecognized selector sent to instance
So I continued my stupidity with:
#interface NSDecimalNumber (CompareString)
-(NSComparisonResult)compare:(NSString *)string;
#end
#implementation NSDecimalNumber (CompareString)
-(NSComparisonResult)compare:(NSString *)string{
NSString *decimalString = self.stringValue;
return[decimalString compare:string options:NSCaseInsensitiveSearch];
}
Now if you compare two NSDecimalNumber the above will be called and the parameter "string" NSDecimalNumber, even though "string" declared NSString, resulting in "unrecognized selector sent to instance" once again.

Core Plot: Exception 'Number of x and y values do not match'

I am unable to find a whole lot of information about this and I'm having zero luck in any way that I try to narrow down where this problem is coming from so I'm hoping somebody here can give me a bit more information and potential leads on why I might be getting this error.
I'm plotting a data set in real time as the data set is constantly increasing through me constantly receiving new data. When I receive new data I take the time i receive it as the x and the value itself as y, this is how I generate my points.
Full Error: Terminating app due to uncaught exception 'CPTException', reason: 'Number of x and y values do not match'
I have looked at my data set before the crash, I have made sure my point creation was never failing neither had anything wrong with them. I'm guessing at this point that is has something to do with my version of Scatter Plot, probably in the numberOfRecordsForPlot function. It doesn't seem to crash anywhere in that function however. The crash doesn't happen until usually 10+ seconds in, but again its not consistent, and before it crashes and am getting perfectly working plotting.
Any light people can shed on this is very much appreciated.
PS: If people want to see code, let me know what, anything non standard I have verified to be functioning to the best of my ability, and anything to do with Scatter Plot is fairly standard.
-(NSUInteger)numberOfRecordsForPlot:(CPTPlot *)plot
{
//Translation: The array with key of the top of the first selected parameter
NSInteger curCount = [self.graphParams count];
NSLog(#"Current Count: %d", curCount);
if ([plot.identifier isEqual:#"Sel_1"] && (curCount >= 1) ) {
if ([self.graphParams objectAtIndex: 0] != nil) {
//NSString *myText = ((UITableViewCell *)[self.graphParams objectAtIndex: 0]).textLabel.text;
//NSInteger myNum = [[self.graphData objectForKey: myText] count];
//return [[self.graphData objectForKey: myText] count];
//return [[self.graphData objectForKey: ((UITableViewCell *)[self.graphParams objectAtIndex: 0]).textLabel.text] count];
return [[self.graphData objectForKey: [self.graphParams objectAtIndex: 0]] count];
}
else
return 0;
}
else if ([plot.identifier isEqual:#"Sel_2"] && (curCount >= 2) ) {
if ([self.graphParams objectAtIndex: 1] != nil)
//return [[self.graphData objectForKey: ((UITableViewCell *)[self.graphParams objectAtIndex: 1]).textLabel.text] count];
return [[self.graphData objectForKey: [self.graphParams objectAtIndex: 1]] count];
else
return 0;
}
else if ([plot.identifier isEqual:#"Sel_3"] && (curCount >= 3) ) {
if ([self.graphParams objectAtIndex: 2] != nil)
//return [[self.graphData objectForKey: ((UITableViewCell *)[self.graphParams objectAtIndex: 2]).textLabel.text] count];
return [[self.graphData objectForKey: [self.graphParams objectAtIndex: 2]] count];
else
return 0;
}
return 0;
}
-(NSNumber *)numberForPlot:(CPTPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index
{
//Translation: The array with key of the top of the first selected parameter
NSValue *value = nil;
if ( [plot.identifier isEqual:#"Sel_1"] ) {
value = [[self.graphData objectForKey: [self.graphParams objectAtIndex:0]] objectAtIndex:index];
}
else if ( [plot.identifier isEqual:#"Sel_2"] ) {
value = [[self.graphData objectForKey: [self.graphParams objectAtIndex: 1]] objectAtIndex:index];
}
else if ( [plot.identifier isEqual:#"Sel_3"] ) {
value = [[self.graphData objectForKey: [self.graphParams objectAtIndex: 2]] objectAtIndex:index];
}
if (value != nil)
{
CGPoint point = [value CGPointValue];
if ( fieldEnum == CPTScatterPlotFieldX )
return [NSNumber numberWithFloat:point.x];
else if ( fieldEnum == CPTScatterPlotFieldY )
return [NSNumber numberWithFloat:point.y];
}
return [NSNumber numberWithFloat:0];
}
EDIT: Posted some scatter plot code where I think error may be coming from, but I dont know how useful this is to any of you. As always comment for additional requests and I'll be happy to provide anything that makes sense.
Make sure all access to the graphData dictionary and its contents are thread-safe. Core Plot does all of its datasource access and drawing on the main thread.
Always call -reloadData, -insertDataAtIndex:numberOfRecords:, and other Core Plot methods from the main thread.
I have also seen this. The exception happens when drawing the graph, not calling any of the data source functions.
Number of x and y values do not match
(
0 CoreFoundation 0x00007fff88f4df56 __exceptionPreprocess + 198
1 libobjc.A.dylib 0x00007fff851cfd5e objc_exception_throw + 43
2 CoreFoundation 0x00007fff88f4dd8a +[NSException raise:format:arguments:] + 106
3 CoreFoundation 0x00007fff88f4dd14 +[NSException raise:format:] + 116
4 CorePlot 0x0000000100027c31 -[CPTScatterPlot renderAsVectorInContext:] + 561
5 CorePlot 0x000000010004dd50 -[CPTLayer drawInContext:] + 96
6 CorePlot 0x000000010001d023 -[CPTPlot drawInContext:] + 99
7 QuartzCore 0x00007fff8a673701 CABackingStoreUpdate_ + 3221
8 QuartzCore 0x00007fff8a672616 _ZN2CA5Layer8display_Ev + 1086
9 QuartzCore 0x00007fff8a66a4e6 _ZN2CA5Layer17display_if_neededEPNS_11TransactionE + 560
10 QuartzCore 0x00007fff8a66949b _ZN2CA7Context18commit_transactionEPNS_11TransactionE + 319
11 QuartzCore 0x00007fff8a669218 _ZN2CA11Transaction6commitEv + 274
12 QuartzCore 0x00007fff8a668819 _ZN2CA11Transaction17observer_callbackEP19__CFRunLoopObservermPv + 63
13 CoreFoundation 0x00007fff88f0d8e7 __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 23
14 CoreFoundation 0x00007fff88f0d846 __CFRunLoopDoObservers + 374
15 CoreFoundation 0x00007fff88ee24a2 CFRunLoopRunSpecific + 258
16 HIToolbox 0x00007fff8d59c4d3 RunCurrentEventLoopInMode + 277
17 HIToolbox 0x00007fff8d5a3781 ReceiveNextEventCommon + 355
18 HIToolbox 0x00007fff8d5a360e BlockUntilNextEventMatchingListInMode + 62
19 AppKit 0x00007fff87df4e31 _DPSNextEvent + 659
20 AppKit 0x00007fff87df4735 -[NSApplication nextEventMatchingMask:untilDate:inMode:dequeue:] + 135
21 AppKit 0x00007fff87df1071 -[NSApplication run] + 470
22 AppKit 0x00007fff8806d244 NSApplicationMain + 867
23 0x0000000100001a62 main + 34
24 0x0000000100001a34 start + 52
)
My app is also MultiThreaded, but I have made sure that [thePlot setDataNeedsReloading] is called in the main thread, and I have ensured that all my data source callbacks are being called in the main thread.
I'm sure that somehow, CorePlot is making two calls to get my data, and I'm adding more data in between those 2 calls, and CorePlot is confused.

showing elements of dictionary

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
}

Variable is Not A CFString Error

Hey fellas, while running through a debugger I am seeing the following appear the second time it sets the variables (timestamp and checksum are set through this method one after the other, it works fine when no DataFeedManager exists, but upon returning to it again it crashes when it's time to set the checksum):
Here is the function of interest:
//sets specified attribute to the passed in value while ensuring that only one instance of the DataFeedManager exists
-(void)setItemInDFMWhilePreservingEntityUniquenessForItem:(attribute)attr withValue:(id)value {
SJLog(#"CoreDataSingleton.m setItemInDFMWhilePreservingEntityUniquenessForItem");
NSError *error;
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription
entityForName:#"DataFeedManager" inManagedObjectContext:[self managedObjectContext]];
[fetchRequest setEntity:entity];
NSUInteger numEntities = [[self managedObjectContext] countForFetchRequest:fetchRequest error:&error];
if (numEntities == NSNotFound) { // ERROR
//...
} else if (numEntities == 0) {
DataFeedManager *dfm = (DataFeedManager *)[NSEntityDescription insertNewObjectForEntityForName:#"DataFeedManager"
inManagedObjectContext:[self managedObjectContext]];
if (attr == checksumAttr) { //BLOCK OF INTEREST
NSString *tempVal = [[NSString alloc] initWithString:value];
[dfm setLastUpdateCheckSum:[NSString stringWithString:tempVal]];
} else if (attr == timeStampAttr) {
[dfm setTimeStamp:value];
}
} else { // more than zero entities
if (numEntities == 1) {
NSArray *fetchedObjects = [[self managedObjectContext] executeFetchRequest:fetchRequest error:&error];
if (attr == checksumAttr) { //BLOCK OF INTEREST
NSString *tempVal = [[NSString alloc] initWithString:value];
[[fetchedObjects objectAtIndex:0] setLastUpdateCheckSum:[NSString stringWithString:tempVal]]; //crashes at this line, after successfully going through the previous BLOCK OF INTEREST area
} else if (attr == timeStampAttr) {
[[fetchedObjects objectAtIndex:0] setTimeStamp:value];
}
} else { // ERROR: more than one entity
//...
}
} // else more than zero entities
[fetchRequest release];
}//setItemInDFMWhilePreservingEntityUniquenessForItem:withValue:
I have marked the areas of interest with //BLOCK OF INTEREST comments and have indicated upon which line the crash occurs (scroll right to see it!). Here is a readout of error from the console:
2011-04-22 17:18:10.924 Parking[26783:207] CoreDataSingleton.m setItemInDFMWhilePreservingEntityUniquenessForItem
2011-04-22 17:18:10.924 Parking[26783:207] -[__NSCFDictionary length]: unrecognized selector sent to instance 0xac34850
2011-04-22 17:18:10.970 Parking[26783:207] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFDictionary length]: unrecognized selector sent to instance 0xac34850'
*** Call stack at first throw:
(
0 CoreFoundation 0x011a0be9 __exceptionPreprocess + 185
1 libobjc.A.dylib 0x012f55c2 objc_exception_throw + 47
2 CoreFoundation 0x011a26fb -[NSObject(NSObject) doesNotRecognizeSelector:] + 187
3 CoreFoundation 0x01112366 ___forwarding___ + 966
4 CoreFoundation 0x01111f22 _CF_forwarding_prep_0 + 50
5 Foundation 0x00c4d1e1 -[NSPlaceholderString initWithString:] + 162
6 Foundation 0x00c562c2 +[NSString stringWithString:] + 72
7 Parking 0x0000e4d4 -[CoreDataSingleton setItemInDFMWhilePreservingEntityUniquenessForItem:withValue:] + 774
8 Parking 0x00008bb4 -[DataUpdater allDataRetrievedWithSuccess:withError:] + 225
9 Parking 0x0000952e -[DataUpdater dataDownloadCompleted:forFunc:withData:withError:] + 769
10 Parking 0x00010bb5 -[DataRetriever finish] + 432
11 Parking 0x00010e75 -[DataRetriever connectionDidFinishLoading:] + 36
12 Foundation 0x00c61172 -[NSURLConnection(NSURLConnectionReallyInternal) sendDidFinishLoading] + 108
13 Foundation 0x00c610cb _NSURLConnectionDidFinishLoading + 133
14 CFNetwork 0x0348e606 _ZN19URLConnectionClient23_clientDidFinishLoadingEPNS_26ClientConnectionEventQueueE + 220
15 CFNetwork 0x03559821 _ZN19URLConnectionClient26ClientConnectionEventQueue33processAllEventsAndConsumePayloadEP20XConnectionEventInfoI12XClientEvent18XClientEventParamsEl + 293
16 CFNetwork 0x03559b0f _ZN19URLConnectionClient26ClientConnectionEventQueue33processAllEventsAndConsumePayloadEP20XConnectionEventInfoI12XClientEvent18XClientEventParamsEl + 1043
17 CFNetwork 0x03484e3c _ZN19URLConnectionClient13processEventsEv + 100
18 CFNetwork 0x03484cb7 _ZN17MultiplexerSource7performEv + 251
19 CoreFoundation 0x0118201f __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 15
20 CoreFoundation 0x010e019d __CFRunLoopDoSources0 + 333
21 CoreFoundation 0x010df786 __CFRunLoopRun + 470
22 CoreFoundation 0x010df240 CFRunLoopRunSpecific + 208
23 CoreFoundation 0x010df161 CFRunLoopRunInMode + 97
24 GraphicsServices 0x01414268 GSEventRunModal + 217
25 GraphicsServices 0x0141432d GSEventRun + 115
26 UIKit 0x0004e42e UIApplicationMain + 1160
27 Parking 0x00002698 main + 102
28 Parking 0x00002629 start + 53
)
terminate called after throwing an instance of 'NSException'
I believe it has something to do with copying the string adequately (can't set a string I don't own to the store). I have tried placing [value copy] as well as &value(saw this sort of thing work for someone else, so I thought I would give it a shot) to no avail. Shouldn't my current method adequately take ownership of the string? I still can't figure out what I am doing wrong. Any help appreciated. Thanks!
Best guess (based in part on this answer) is that you're passing in a released object as the value when you call the method the second time, or possibly that value is of class NSDictionary on your second time through – it's not clear from this code snippet why your method takes an argument of type id and then blithely treats it as an instance of NSString, but this may be part of the problem.
Note that your -setItemInDFMWhilePreservingEntityUniquenessForItem:withValue: accepts an arbitrary object in its second argument (type id).
Inside the method, you do:
NSString *tempVal = [[NSString alloc] initWithString:value];
Unless value is an Objective-C string, this will crash your program. In fact, your crash log shows that in that particular execution value was an NSDictionary. You need to make sure that value is an NSString.
Also, note that you own the string you’re assigning to tempVal since you’ve used +alloc. Don’t forget to release that string.

how do I catch a NSRangeException?

I want my app to continue gracefully when the online server messes up. I tried to wrap the dangerous line in a #try block. Yet it is still crashing like so:
the method:
+ (NSArray *)findAllFor:(NSObject *)ratable {
NSString *ratingsPath = [NSString stringWithFormat:#"%#%#/%#/%#%#",
[self getRemoteSite],
[ratable getRemoteCollectionName],
[ratable getRemoteId],
[self getRemoteCollectionName],
[self getRemoteProtocolExtension]];
Response *res = [ORConnection get:ratingsPath withUser:[[self class] getRemoteUser]
andPassword:[[self class] getRemotePassword]];
NSArray *ratings;
#try {
ratings = [self fromXMLData:res.body];
}
#catch (NSException *e) {
ratings = [NSArray array];
}
return ratings;
}
the stack trace:
Program received signal: “SIGABRT”.
2010-08-07 16:38:51.846 TalkToHer[68608:7003] *** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[NSArray objectAtIndex:]: index 1 beyond bounds [0 .. 0]'
*** Call stack at first throw:
(
0 CoreFoundation 0x02932919 __exceptionPreprocess + 185
1 libobjc.A.dylib 0x02a805de objc_exception_throw + 47
2 CoreFoundation 0x0292858c -[__NSArrayI objectAtIndex:] + 236
3 TalkToHer 0x00009fa7 -[FromXMLElementDelegate parser:didEndElement:namespaceURI:qualifiedName:] + 425
4 Foundation 0x0017bcc1 _endElementNs + 453
5 libxml2.2.dylib 0x02d9deb6 xmlParseXMLDecl + 1353
6 libxml2.2.dylib 0x02da8bc1 xmlParseChunk + 3985
7 Foundation 0x0017b4c2 -[NSXMLParser parse] + 321
8 TalkToHer 0x0000b14d +[NSObject(XMLSerializableSupport) fromXMLData:] + 201
9 TalkToHer 0x00031a6c +[Rating findAllFor:] + 320
10 TalkToHer 0x00032d67 -[FirstClassContentPiece(Ratable) updateRatings] + 96
11 TalkToHer 0x00004d5f __-[InspirationController tableView:didSelectRowAtIndexPath:]_block_invoke_3 + 33
12 libSystem.B.dylib 0x9792efe4 _dispatch_call_block_and_release + 16
13 libSystem.B.dylib 0x97921a4c _dispatch_queue_drain + 249
14 libSystem.B.dylib 0x979214a8 _dispatch_queue_invoke + 50
15 libSystem.B.dylib 0x979212be _dispatch_worker_thread2 + 240
16 libSystem.B.dylib 0x97920d41 _pthread_wqthread + 390
17 libSystem.B.dylib 0x97920b86 start_wqthread + 30
)
terminate called after throwing an instance of 'NSException'
Is my syntax for #try #catch wrong? I attempted to add a #catch block for NSRangeException but it seems that's not the right approach (it's not a class).
Also, the server error is caused by [ratable getRemoteId] sometimes returning (null) instead of an integer. This behavior seems pretty unpredictable; if anyone has a clue why ObjectiveResource might be doing that it would be helpful. But I still would like to know how to use #try #catch.
As I now understand it, throwing exceptions should only be done to alert users of your library that they have made a programming error. I am still curious why the syntax I used did not prevent the crash. I know the error was occurring several levels down; but the #try {} #catch {} block should handle all methods called by the methods I call...
At any rate, here is the fixed code, for anyone who wants to fetch scoped objects from a Rails-style restful resource.
+ (NSArray *)findAllFor:(NSObject *)ratable {
NSString *ratingsPath = [NSString stringWithFormat:#"%#%#/%#/%#%#",
[self getRemoteSite],
[ratable getRemoteCollectionName],
[ratable getRemoteId],
[self getRemoteCollectionName],
[self getRemoteProtocolExtension]];
Response *res = [ORConnection get:ratingsPath withUser:[[self class] getRemoteUser]
andPassword:[[self class] getRemotePassword]];
NSError **aError;
if([res isError]) {
*aError = res.error;
return nil;
}
else {
return [self performSelector:[self getRemoteParseDataMethod] withObject:res.body];
}
}
You don't. You fix your code to not throw an exception under these circumstances.