TableView doesn't allow for 'section' in dictionary - objective-c

I want to loop through a list of json items to use in my sectioned tableView. For this I would like to restructure the data to have a section->array setup, where array contains an array of sessions.
First of all, I don't know if this is the preferred way to go, there may be easier ways. I keep getting the error that I am not allowed to use 'section' as an identifier in the dictionary. Moreover, when I use something else than a 'section' the dictionary keeps getting overridden.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
NSString *day = _json[#"days"][3];
NSString *key;
NSUInteger count = 0;
NSMutableArray *sessionList = [[NSMutableArray alloc] init];
NSArray *timeslotsSorted = [[_json[#"schedule"][day] allKeys]
sortedArrayUsingSelector:#selector(localizedCaseInsensitiveCompare:)];
NSArray *locationsSorted = [[_json[#"schedule"][day][timeslotsSorted[section]] allKeys]
sortedArrayUsingSelector:#selector(localizedCaseInsensitiveCompare:)];
for (key in locationsSorted) {
NSDictionary *temp = _json[#"schedule"][day][timeslotsSorted[section]][key];
if ([temp isKindOfClass:[NSDictionary class]]) {
[sessionList addObject:temp[#"title"]]; //test array
count++;
}
}
_sessionDict = #{
section: sessionList
};
return count;
}

You are doing all the work to build your data structure in the wrong place. Lets say there are 10 sections in your data. This will call the tableView: numberOfRowsInSection method 10 times which makes this a pretty inefficient place to do much work. You will also have to implement the method that returns the number of sections to show, and the method to display each individual row.
I would build my data structures in the viewWillLoad method and then store it locallaly and reuse it in all the tableView methods.

First, this is what NSInteger is:
typedef int NSInteger;
You must wrap it into an object. Something like:
[NSNumber numberWithInteger:section]
And than add it to your dictionary.

i don't really know that your timeslotsSorted and locationsSorted contain right items, but lets say they do. I would recommend you to have this sorting before - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section and - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView; are called.
Lets say, you received JSON, so you have to parse it as you do, and then call [tableView reloadData] or reload visible cells with animations.
and then your tableView data source methods will be called and you will do something like:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return [sessionList count];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
NSString* key = [self.sessionList objectAtIndex:section];
return [[self.secions objectForKey:key] count];
}
and don't forget to make strong properties for self.sections and self.sessionList

Related

Search for object in NSMutableArray and change value for that object

I have project where user can add some Items to TableView. My data source for this TableView are objects with 2 properties NSString * nameOfItem and NSNumber * numberOfItem. Is any possibility to check my NSMutableArray if it contain string #"someString" as property nameOfItem and if yes than change numberOfItem +1 ?
UPDATE:
I try to do it with for(...in...) but it works just when i have only one object in my NSMutableArray. If i have more objects there it create one new object and than change value to ++ on old one:
Here is some code what i tried:
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
NSString*nameToCheck = [NSString stringWithFormat:#"%#", [self.ivc.objects objectAtIndex:indexPath.row]];
for (Items *itemNamed in self.ivc.shoppingList.items) {
if ([itemNamed.nameOfItem isEqualToString:nameToCheck]) {
[itemNamed setNumberOfItem:[NSNumber numberWithInt:[itemNamed.numberOfItem integerValue]+1.0]];
} else {
Items *item = [Items new];
[item setNameOfItem:name];
[item setNumberOfItem:#(1)];
[self.ivc.shoppingList.items insertObject:item atIndex:0];
}
I want to create new one only if is not yet in that list.
Any help appreciated.
I don't know something like this but you can use a NSDictionary instead of NSArray using the name property as a key. And if you don't want to do that, you can sort the array and make a binary search for element.

Adding object to a column in a cell-based NSTableView?

I'm having trouble with Columns in NSTableview. I want to add an item to a specific column in an instance of NSTableView. (Note that data is a pointer to an instance of NSMutableArray, which is a property of AppDelegate, which is the dataSource)
-(IBAction)addTask:(id)sender
{
[self.data addObject:#""];
[self tableView:_tableView setObjectValue:#"Hello World" forTableColumn: self.column row:0];
[self.tableView reloadData];
}
A tutorial I went through showed me how to edit a single-column NSTableView. However, using the same implementation of the NSTableViewDataSource methods causes tableView to populate both columns. The pertinent implementation from the tutorial:
-(void)tableView:(NSTableView *)tableView
setObjectValue:(id)object
forTableColumn:(NSTableColumn *)tableColumn
row:(NSInteger)row
{
[self.data replaceObjectAtIndex:row withObject:object];
}
I reason part of the issue is that the above method doesn't do anything with the tableColumn parameter, but I'm still learning and have no idea how to proceed. (It's especially hard to find help because many modern tutorials involve view-based NSTableViews, and well I know that is best practice, I don't want to run away from this.) I hope my explanation was clear enough, and any help would be much appreciated.
The reason you are seeing the data populated in multiple columns is you are not differentiating what values go in what columns.
You should think of each item in your array as a row in your table view. If you wish to display different values in columns of that row you need a way to store those different values in the data source object. This can be done by using a concrete model object class that has multiple properties defined or by using a NSDictionary with different keys with their corresponding values.
For adding a row:
-(IBAction)addTask:(id)sender
{
NSMutableDictionary *newRow = [NSMutableDictionary dictionary];
[newRow setObject:#"Hello World" forKey:#"salutation"];
[self.data addObject:newRow];
[self.tableView reloadData];
}
So for the display code:
- (id)tableView:(NSTableView *)aTableView objectValueForTableColumn:(NSTableColumn *)aTableColumn row:(NSInteger)rowIndex
{
NSDictionary *row = [self.data objectAtIndex:rowIndex];
NSString *columnIdentifier = [aTableColumn identifier];
return [row objectForKey:columnIdentifier];
}
You'll notice we are using the column identifier here. Normally you set this value in Interface Builder on the table column. In the case above the identifier needs to be the same as the key in the dictionary for which you wish to display information.
Finally allowing the user to set a value of a column in the table view:
-(void)tableView:(NSTableView *)aTableView setObjectValue:(id)anObject forTableColumn:(NSTableColumn *)aTableColumn row:(NSInteger) rowIndex
{
NSDictionary *row = [self.data objectAtIndex:rowIndex];
NSString *columnIdentifier = [aTableColumn identifier];
[row setValue:anObject forKey:columnIdentifier];
}

Adding data to a tableView using a NSMutableArray

I'm having a problem adding an item to my tableView.
I used to initialize an empty tableView at the start of my App and get it filled with scanned items every time the tableView reappears and there is an item in my variable.
Initialization of the tableView:
NSMutableArray *array = [[NSMutableArray alloc] initWithObjects:nil];
self.listArray = array;
TableView Data Source:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return [self.listArray count];
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
if(section == 0)
return #"Eingescannte Artikel:";
else
return nil;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"testCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
// Configure the cell...
NSUInteger row = [indexPath row];
cell.textLabel.text = [listArray objectAtIndex:row];//[NSString stringWithFormat:#"Das ist Zeile %i", indexPath.row];
return cell;
}
(Not the whole thing but the ones I changed)
As you may have seen I use an NSMutableArray to add items to my tableView.
So if an item ist scanned I'm adding it to my array like this:
[listArray insertObject:sharedGS.strEAN atIndex:0]; //using a shared Instance where I implemented my variable.
I also tried to use an variable to extend my Index every time a new Item is added, but it won't work both ways.
I'm quite new to programming so an not-too-hard-to-understand-answer would be quite nice ;)
If there's any information missing, feel free to ask.
/edit: Trying to specify my question: The data from the variable is written in a TableViewCell, but if I scan another one the other one is just being replaced. Not sure if it's a problem with my array or my tableView...
/edit No.2: Found out(thanks to fzwo) that my array isn't working correctly. It just doesn't grow by an addObject: or insertObject:atIndex: command. But I just don't get why... :(
All I'm doing: [listArray addObject:sharedGS.strEAN]; not that much space for errors in one simple line. Maybe I'm just too stupid to recognize what I'm doing wrong:D
You state that your problem is "adding an item to my tableView" , since you are adding the object to your array i am guessing the problem is that you are not reloading the table or that it is missing the dataSource binding.
You have not actually asked any question (even if you added info to "specify your question") so a wild guess, after
[listArray insertObject:sharedGS.strEAN atIndex:0];
put
[yourTableView reloadData];
Are you intentionally adding new items to the top of the table ? otherwise you could do
[listArray addObject:sharedGS.strEAN]; to add new items to the bottom
Otherwise it's worth noting that you are misusing dequeueReusableCellWithIdentifier, look at the example below for proper usage:
// Try to retrieve from the table view a now-unused cell with the given identifier
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
// If no cell is available, create a new one using the given identifier
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:MyIdentifier] autorelease];
}

setting UITableViewCell to value from custom object instance

So basically I am trying to create instances of the class below every time I received a valid response from a web request and then store those instances in an array so I can access their data later. Then, I try to populate a table view with specific fields from the instance(s) that are stored in the array. I've been having some issues since I am very familiar with C++ and do this sort of thing with vectors and then just access based off of the index I need, but this has had me pulling my hair out! Thanks, code is below:
eventDetails.h:
#interface eventDetails : NSObject {
NSString *eventName, *eventID;
}
-(void) setEventID : (NSString *) ID;
-(void) setEventName: (NSString *) name;
-(NSString *) getEventName;
-(NSString *) getEventID;
and also note that
NSMutableArray *events
is declared in my .h file and
events = [[NSMutableArray alloc] init];
has been called in the viewDidLoad
I then dynamically create instances as a response is received from an web request and add them to an array:
if ([elementName isEqualToString:#"id"])
{
NSLog(#"at beginning of event, length is %i", [events count]);
temp = [[eventDetails alloc] init];
[temp setEventID:[NSMutableString stringWithString:soapResults]];
[soapResults setString:#""];
elementFound = FALSE;
}
if ([elementName isEqualToString:#"name"])
{
[temp setEventName:[NSMutableString stringWithString:soapResults]];
[events addObject:temp];
[soapResults setString:#""];
elementFound = FALSE;
//[temp release];
}
After everything is all said and done, I created a little test function to ensure the data was set correctly:
-(void) test{
for (eventDetails *s in events){
NSLog(#"Entry ID: %# with name %#", [s getEventID], [s getEventName]);
}
}
and I get the following (correct) output:
2011-04-09 18:53:24.624 Validator[90982:207] Entry ID: 701 with name iPhone Test Event
2011-04-09 18:53:24.625 Validator[90982:207] Entry ID: 784 with name Another iPhone Test Event
2011-04-09 18:53:24.626 Validator[90982:207] Entry ID: 839 with name third iphone
I then try to refresh the table view, and have it pull in data from the instances in the array:
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
//---try to get a reusable cell---
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
//---create new cell if no reusable cell is available---
if (cell == nil) { cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifier] autorelease];
}
//---set the text to display for the cell---
eventDetails *cellDetails = [[eventDetails alloc] init];
NSInteger row = [indexPath row];
cellDetails = [[self events] objectAtIndex:row];
NSString *cellValue = [cellDetails getEventName];
NSLog(#"Event is: %#", cellValue);
cell.textLabel.text = cellValue;
cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
return cell;
}
But every time the program gets to this part, it crashed which a EXC_BAD_ACCESS where I say:
cell.textLabel.text = cellValue;
Thanks for your help. I think I might be doing something wrong with how I declare the instances of the eventDetails class, but I am not sure since it is working correctly as far as storing that data. If you need any more code, I have the missing sections.
There are too many omitted details in the code you posted to know for sure, but my guess would be the eventName isn't retained, and is deallocated sometime before you attempt to use it.
Check your setEventName: implementation; it would need to send either retain or copy to the name argument to ensure that the string won't be deallocated before you're done using it. However, the situation is more complex than that if you want to avoid memory leaks, so you if you haven't done so already, I'd recommend reading up on memory management, in particular, Apple's excellent Memory Management Programming Guide. (Note: I've given up posting links since Apple keeps changing them).
A side note: don't prefix the names of accessor methods with the word get; that would be fine in Java or C++, but this is Objective-C. Your accessors should look like this:
- (NSString *)eventName;
- (NSString *)eventID;
There's no guarantee that Foundation mechanisms that rely on introspection will work correctly with accessors that don't follow the documented naming conventions, so that's another thing to read up on. :-)

NSPasteboard type for NSManagedObject

I need to drag a reference to an NSManagedObject between two table views of my application. What's the preferred NSPasteboard type to store a reference to an NSManagedObject?
My current solution is to store the URIRepresentation of the object's NSManagedObjectID in a NSPasteboardTypeString. I suspect there's a more elegant solution out there.
There is no standard type for all model objects since your model objects and how they're handled are unique to your application. If there was one pasteboard type for all then there'd be no telling them apart. Your own custom object should have its own drag type.
Just use a string that makes sense (maybe a #define so you can find it with auto-complete in Xcode) like "MyObjectPboardType" that resolves to "com.yourcompany.yourapp.yourobjecttype".
Use NSPasteboard's -declareTypes:owner: to declare your new type, then use -setString:forType: or one of the other -set?:forType: methods to set the information for your object's type. In your case, the use of the object ID is a perfectly acceptable identifier. Just remember managed objects' object IDs change when they're new versus persisted.
If you are dragging within tables in the same application you might as well put in pasteboard the rowIndexes (indexPaths in case you are dragging from an outlineView) of the objects in the tableView (outlineView). This might as well spare you from some unneeded CoreData access if the dataSource of the tableViews are NSArrayController (NSTreeController for outlineView).
You can then easily retrieve the dragged objects when accepting the drop since the ‘info‘ object passed to both methods ‘tableView:validateDrop:proposedRow: proposedDropOperation:‘ and to ‘tableView:acceptDrop:row:dropOperation:‘ will have a reference to the tableView originating the drag under ‘draggingSource‘ key path.
Here's a simple implementation:
extern NSString *const kMyLocalDragType = #"com.whatever.localDragType";
#implementation MyArrayControllerDataSource
.
.
.
#pragma mark - NSTableViewDataSource (Drag & Drop)
+ (NSArray *)dragTypes {
// convenience method returning all class's supported dragTypes
return #[kMyLocalDragType];
}
- (BOOL)tableView:(NSTableView *)tableView writeRowsWithIndexes:(NSIndexSet *)rowIndexes toPasteboard:(NSPasteboard *)pboard {
[pboard declareTypes:[[self class] dragTypes] owner:self];
for (NSString *aDragType in [[self class] dragTypes]) {
if (aDragType == kMyLocalDragType) {
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:rowIndexes]; // we are supporting drag&drop of multiple items selected
[pboard setData:data forType:aDragType];
}
.
. // logic for other dragTypes
.
}
return YES;
}
- (NSDragOperation)tableView:(NSTableView *)tableView validateDrop:(id<NSDraggingInfo>)info proposedRow:(NSInteger)row proposedDropOperation:(NSTableViewDropOperation)dropOperation {
NSArray *dragTypes = [info draggingPasteboard] types];
for (id aDragType in dragTypes) {
if (aDragType == kMyLocalDragType) {
return NSDragOperationCopy;
}
}
.
.// Other logic for accepting drops/affect drop operation
.
}
- (BOOL)tableView:(NSTableView *)tableView acceptDrop:(id<NSDraggingInfo>)info row:(NSInteger)row dropOperation:(NSTableViewDropOperation)dropOperation {
if ([info draggingPasteboard] types] containsObject:kMyLocalDragType]) {
// Retrieve the index set from the pasteboard:
NSData *data = [[info draggingPasteboard] dataForType:kMyLocalDragType];
NSIndexSet *rowIndexes = [NSKeyedUnarchiver unarchiveObjectWithData:data];
NSArray *droppedObjects = [self retrieveFromTableView:tableView objectsAtRows:rowIndexes];
// droppedObjects contains dragged and dropped objects, do what you
// need to do with them, then add them to this dataSource:
[self.content insertObjects:droppedObjects];
[tableView reloadData];
[tableView deselectAll:nil];
return YES;
}
.
. // other logic for accepting drops of other dragTypes supported.
.
}
#pragma mark - Helpers
- (NSArray <NSManagedObject *> *)retrieveFromTableView:(NSTableView *)tableView objectsAtRowIndexes:(NSIndexSet *)rowIndexes {
id dataSource = [tableView dataSource];
if ([dataSource respondsToSelector:#selector(content)]) {
if ([dataSource.content respondsToSelector:#selector(objectsAtIndexes:)]) {
return [datasource content] objectsAtIndexes:rowIndexes];
}
}
return #[]; //We return an empty array in case introspection check failed
}