best way of handling self-changing array of information - iphone

This question is about handling arrays of information, there's are many ways I could do this, but I would like some input from programmers with more experience, I know what I want to do just not how to organize the information the best way, and objective-C is really making me ponder this, I don't want to get 100 hours into work a decide, oops this wasted the beast way to do this. So here goes:
I have a grid where I'm simulating a playing field, each piece of the grid I call a cell. The cells have around 20 different values each, all integers, nothing fancy. A change to a cell will be either by player input, or occur or by surrounding cells through different algorithms.
The changes to cells will occur once a turn is complete, so it's not real time. Now, I'm not even sure about doing this with a MutableArrays, a plain Array, or just a plain matrix. Arrays are good at keeping such info for one dimension, but I would imagine would become quite cumbersome if you have to address a batch of 10,000 of these cells. On the other hand a simple matrix might not be so elegant, but probably easier to work with.
Any insight would be greatly appreciated.

You have two options here that I see:
1) Use standard containers
Assuming that the playing field is of constant size, then you can create a mutable array of x*y size, and populate it with mutable dictionaries. By giving everything in the second mutable dictionary keys, you can query and set their properties (all objects of course, so wrap ints in NSNumbers etc). For indexing use a macro INDEX_FROM_ROW_COL(row, col) and apply the appropriate code to multiply/add.
2) Create a helper object subclassed from NSObject. It would manage mutable objects as above, but you could load it with functionality specific to your application. You could provide methods that have parameters of "row:" and "col:". Methods that change or set properties of each cell based on some criteria. Personally, I think this is a better idea as you can incapsulate logic here and make the interface to it more high level. It will make it easier to log whats going on too.

Related

swift array 'contains' function in place optimization

I am wondering if the built-in array structure for the contains function has any optimizations. If it does a linear search of contains every time I run it, it's at best O(n), which turns into O(n^2) because I'll be looping through another set of points to check against, however if it somehow behind the scenes sorts the array the first time 'contains' is run, then every subsequent 'contains' would be O(log(n)).
I have an array that gradually gets larger the more in depth the user gets into the application, and I am using the 'contains' a lot, so I am expecting it to slow down the application the longer the user is using the application.
If the array doesn't have any behind the scenes optimizations, then ought I build my own? (e.g. quicksort, and do an insert(newElement:, at:) every time I add to the array?)
Specifically, I'm using
[CGPoint],
CGPointArrayVariable.contains(newCGPoint) // run 100s - 10000s of times ideally every frame, (but realistically probably every second)
and when I add new CGPoints I'm using
CGPointArrayVariable += newCGPointSet.
So, the question: Am I ok continuing to use the built in .contains function (will it be fast enough?) or should I build my own structure optimizing for the contains, and keeping the array sorted? (maybe an insertion sort would be better to use opposed to a quicksort, if that's the direction recommended)
Doing something like that every frame will be VERY inefficient.
I would suggest re-thinking your design to avoid tracking that amount of information for every frame.
If it's absolutely necessary, building your own Type that uses a Dictionary rather than an Array should be more efficient.
Also, if it works with your use case using a Setmight be the best option.

Dynamically declaring number of buttons in a for loop in Swift

Is there a way to dynamically declare a certain number of UIButtons based on the number of iterations in a for loop?
the actual number would be passed in from the user or based on an array length
so pseudo-code would be
for num in total{
//declare a UIbutton with a unique name
}
If you are using UITableView the best way to accomplish this is using the table own behavior to populate its cells automatically with your source date (array, dictionaries, etc) even with data gathered from external sources like a REST service.
The way to do this is creating a custom cell with each outlet and point them to your sources.
After some googling, I think this is called metaprogramming and that swift doesn't have it yet :(
edit: looks like i was way overthinking things. this is actually fairly straightforward if i think about it without looping

Efficiently accessing array within array

I have a data type called Filter which has an NSMutableArray property which holds a bunch of FilterKey objects (different amount of keys for each filter). I have a bunch of these Filter objects stored in an NSMutableArray called Filters.
I have a UITableView for which each row is populated with data from one of the FilterKey objects. My question is, for a given row in the UITableView, how can I use the Filters array to find the right FilterKey (considering I've already put the Filters and Keys in order manually)?
Basically, I know I could just traverse through the Filters array and for each Filter object, traverse through all it's FilterKeys, but I'm wondering is there a better way to do this (ie better data structure, or something that would give me the right object faster?
Sorry if this is confusing if you have any questions please let me know in the comments.
Typically you would use sections and rows for this, where each section is a Filter and each row is a FilterKey.
It sounds like you just want to show the filter keys, and not have section headers for their filters (if I'm reading your post correctly). If you don't actually want headers, that's fine, just return 0 for tableView:heightForHeaderInSection: and nil for tableView:viewForHeaderInSection:.
All of this is really more for convenience than performance. It is unlikely that it will be much faster than running through the filters and adding up the counts of their keys. That kind of operation is extremely fast. But sections/rows maps your data better, so I'd probably use it anyway to keep the code simpler.
You can use NSMutableDictionary which is hash-mapped resulting in faster, easier, readable operations.
If you prefer arrays then there is no need to traverse to search for a specific value, you can use NSPredicate to filter your array.

Objective-C sparse array redux

First off, I've seen this, but it doesn't quite seem to suit my needs.
I've got a situation where I need a sparse array. Some situations where I could have, say 3000 potential entries with only 20 allocated, other situations where I could have most or all of the 3000 allocated. Using an NSMutableDictionary (with NSString representations of the integer index values) would appear to work well for the first case, but would seemingly be inefficient for the second, both in storage and lookup speed. Using an NSMutableArray with NSNull objects for the empty entries would work fairly well for the second case, but it seems a bit wasteful (and it could produce an annoying delay at the UI) to insert most of 3000 NSNull entries for the first case.
The referenced article mentions using an NSMapTable, since it supposedly allows integer keys, but apparently that class is not available on iPhone (and I'm not sure I like having an object that doesn't retain, either).
So, is there another option?
Added 9/22
I've been looking at a custom class that embeds an NSMutableSet, with set entries consisting of a custom class with integer (ie, element#) and element pointer, and written to mimic an NSMutableArray in terms of adds/updates/finds (but not inserts/removals). This seems to be the most reasonable approach.
A NSMutableDictionary probably will not be slow, dictionaries generally use hashing and are rather fast, bench mark.
Another option is a C array of pointers. Allocation a large array only allocates virtual memory until the real memory is accessed (cure calloc, not malloc, memset). The downside is that memory is allocated in 4KB pages which can be wasteful for small numbers of entries, for large numbers of entries many may fall in the same page.
What about CFDictionary (or actually CFMutableDictionary)? In the documentation, it says that you can use any C data type as a key, so perhaps that would be closer to what you need?
I've got the custom class going and it works pretty well so far. It's 322 lines of code in the h+m files, including the inner class stuff, a lot of blank lines, comments, description formatter (currently giving me more trouble than anything else) and some LRU management code unrelated to the basic concept. Performance-wise it seems to be working faster than another scheme I had that only allowed "sparseness" on the tail end, presumably because I was able to eliminate a lot of special-case logic.
One nice thing about the approach was that I could make much of the API identical to NSMutableArray, so I only needed to change maybe 25% of the lines that somehow reference the class.
I also needed a sparse array and have put mine on git hub.
If you need a sparse array feel free to grab https://github.com/LavaSlider/DSSparseArray

data structure best practices for UITableView datasource

I am trying to figure out whats the best data structure to hold the data source for a UITableView. I am looking for something as robust as possible - a structure that will hold data for the different sections, and which will enable convenient add and remove of objects. I saw a few implementations using NSMutableArrays and dictionaries, but I am still not convinced as to which approach is the most robust.
Appreciate your help and thoughts.
NSMutableArray is the most efficient since the index path for row and section readily convert to integers which can be used to access the array elements.
Depends on really how complex your data is. If its just couple of strings then an Array of NSStrings will suffice. If its like an image path, a text label and its description then maybe an array of custom class holding that data. I almost always go for the Arrays since you can get your desired object from it with the objectAtIndex:indexPath.row bit.