iPhone: Data structure choice - iphone

I need to keep track of a bunch of objects that can be identified by two keys (Latitude and longitude actually, but there are some other properties). I need to do things like search for a particular object by those two keys, updating it if it is there and inserting if not. I was thinking. I was looking at NSDictionary and NSSet but thought I would hear what the masses have to say.

I guess the simpler way is to use NSDictionary. You will be able to get your data by just doing [dic objectForKey:key].
Also, a good practice is to create some defines for the keys, so that it's easier to change a key name, and also avoids typo:
#define kObjectLatitude #"Latitude"
#define kObjectLongitude #"Longitude"
[object setObject:lat forKey:kObjectLatitude];
[object setObject:lon forKey:kObjectLongitude];
Don't forget to write the defines in a smart place. If you use it only in one class, just write them at the top of the declaration. If, however, you need them through different part of your code, you might consider moving it to the header file of the main class, or a specific header file for defines :)
NS(Mutable)Set will not be useful for you in this case. NSSets are mathematical sets, and you cannot access a specific data with a specific key (aka, you can't ask a set: "Hey, give me the longitude, where-ever you stored it!")

This is not a direct answer, but a word of warning. Latitude and longitude are CLLocationDegrees, which is a double precision floating point value. Testing for equality on floats is a risky proposition since floating point math is inexact. You can easily have an equality test fail on two floats that should theoretically be equal. I don't know the requirements of your application, but you may want to test for proximity rather than equality.

Use NSDictionary. That's what it meant for.

Related

What are the function-call/procedure-call pairs in GAP?

By function-call/procedure-call pairs, I mean pairs of functions that do the same thing, except one returns it's result whereas the other alters it's argument(s) to be the result. For example the pair List/Apply.
List(list, func) Returns the list resulting from applying the function func to every value of list.
Apply(list, func) Applies the function func to every value of a mutable list list, changing list.
I've become annoyed of writing my own functions to find that GAP already had a built in version I should be using, so it'd help to know these pairs. Like, does Filtered have a procedural counterpart I don't know about? Or do I need to write my own? If a function does have a counterpart will it necessarily be listed in the documentation for that function? The only other such pair that I can think of right now is Concatenation/Append. What are other such pairs of functions/procedures in GAP?
Although this may be of little help, as Alexander Hulpke explained in https://math.stackexchange.com/questions/3704518, "The general language convention is that verbs do something to an object, while nouns create a new object with the desired characteristics." GAP naming conventions are described in the GAP Reference Manual here.
So, a counterpart to Filtered would likely be called Filter - but there is no such function (and Filter has another meaning in GAP). We do try to mention counterparts in corresponding manual sections - if you find them missing, then please suggest improvements to the GAP documentation, preferably at the GAP repository on GitHub.

What are the differences betwen immutable and mutable classes?

i studing about c# and i think that the diference betwen mutable & inmutable class , (un c# for example), are that the definitiĆ³n of the variables cant change. The string still string, or may be that the value of the types cant change : string = "Hola" still "Hola". and the mutable can change.
well i am right or what is the real diference?
thank you
An immutable object is an object that can't change it's property values after it's created (actually its state, but to simplify, let's just assume that a different state implies different property/variable values). Any properties are usually asigned values in the constructor (it may not have any properties at all, just methods).
An immutable object can have internal variables that might change values, as long as they don't affect the state of that object from a public/external point of view.
A string in C# is immutable... if you try to assign a string variable a different value, a new string is created.
You can find more information about immutability in OOP on the Wikipedia
PS: it's a bit more complicated than this, but I don't want to confuse you... there are different levels of what can be considered "immutable", but if you want to research further, apart from the Wikipedia article (which doesn't mention C#), there's this post by Eric Lippert which explains the different types way better than I could ever do.

when to use the various sort methods of NSArray?

The doco explains what the NSArray sort methods are, but is anyone able to give a bullet point say on when/why you'd use a particular method? i.e. under what circumstances in you code would you use method XXX over method YYY. For:
sortedArrayUsingComparator
sortedArrayUsingDescriptors
sortedArrayUsingFunction:context
sortedArrayUsingSelector
See Collection Programming Topics: Sorting Arrays for more general information. If you're looking at the class reference documentation, be sure to check out the "Companion guides" that are listed for more practical, real-world advice on how the classes work.
Basically, sortedArrayUsingSelector: and sortedArrayUsingFunction:context: have been around since 10.0/iOS 2.0. They're not as flexible as the other methods which came later.
If you have an array of relatively simple objects, like NSNumbers or NSStrings, you could use [numbers sortedArrayUsingSelector:#selector(compare:)] to easily sort the objects.
If, on the other hand, you have a more complex model object that has multiple properties, such as age, name, date, NSSortDescriptors work well. Those were added in OS X 10.3/iOS 2.0. The allow you to do something like first sort by age, then by name, and then by date.

Is there a way for preprocessor macros to insert arguments without me putting whitespace on either side of it?

To make a somewhat long story short, I'm trying to do this:
#define MY_MACRO(x) id myObjectx;
to create myObject1 and myObject2 and so on. I have a lot of these, and the real situation is a little more complicated than just declaring the object and that's it, I need it to repeat a few different things with that number, and copy-paste is getting ugly.
Note: I understand that with the information I've given you you'll be tempted to suggest I just use an array, so I'll explain - I need a bunch of separate KVO properties, and they can't all go in a to-many because the amount of change notifications would get out of hand.
As bmargulies said, you can use ## in the macro:
#define MY_MACRO(x) id myObject##x;
bmargulies, why don't you add your comment as an answer...?

Solving the NSInteger <-> NSNumber problem

I've written a large social networking iPhone application, and one of the biggest issues I run into is the fact that NSInteger (and all the other NS-non-object types) are not first class citizens. This problem stems from the fact that, obviously, they have no representation for a nil value.
This creates two main problems:
Tons of overhead and opaqueness to convert to and from NSNumber when storing/retrieving from a collection.
Can't represent nil. Oftentimes, I want to be able to represent an "unset" value.
One way to solve this is to use NSNumber all the time, but that gets extremely confusing. In a User model object, I would have about 20 different NSNumbers, and no easy way to tell if each one is a float, integer, bool, etc.
So here are my thoughts for potential solutions and the pros/cons. I'm not really sold on any of them, so I thought I'd ask for feedback and/or alternative solutions to this problem.
Continue to use NSInteger types, and just use NSIntegerMax to represent nil.
PRO - Less memory overhead
PRO - Clear typing
CON - NSIntegerMax is not really nil. If programmers aren't careful or don't know this convention, invalid values could leak into the display layer.
CON - Can't store them in a collection without conversions in and out
Use NSNumber and designate types using hungarian notation (eg NSNumber fHeight, NSNumber iAge)
PRO - First-class citizens
PRO - Nil problem solved
CON - Increased memory overhead
CON - Lose compiler type checking
CON - Hungarian notation is contentious
Write my own first-class primitive object types (think Java http://developer.android.com/reference/java/lang/Integer.html)
PRO - First-class citizens
PRO - Nil problem solved
PRO - Keeps compiler type checking
PRO - Objects will be simpler than NSNumber. Internal storage will specific to data type.
CON - Increased memory overhead
CON - Sacrifices a bit of code portability and compatibility
Looking for a convincing argument in favor of one of these techniques, or one I haven't thought of if you've got one.
UPDATE
I've gone ahead and started an open source project (Apache 2.0), into which I'll be pulling a number of our internal classes as I have time. It currently includes object wrappers for some of the more common native data types (BOOL, CGFloat, NSInteger, NSUInteger). We chose to do this because it upgrades these data types to first class citizens with strict typing. Maybe you disagree with this approach, but it has worked well for us, so feel free to use it if you want.
I'm adding other classes we've found uses for, including a disk-backed LRU cache, a "Pair" object, a low memory release pool, etc.
Enjoy
github - Zoosk/ZSFoundation
The most common convention for representing the idea of nil as an NSInteger is to use the NSNotFound value. This is, in fact, equal to NSIntegerMax, though it tends to be more obvious to the reader that this is a sentinel value representing the lack of a number. There are many cases where this is used throughout Cocoa. One common case is as the location field of an NSRange as a return value from -rangeOfString: et al.
You could try this?
#define numberWithFloat(float f) \
[NSNumber numberWithFloat:f]
#define floatFromNumber(NSNumber *n) \
[n floatValue]
(see my original answer below)
Here's the other thing with NSNumber, you don't have to retrieve what you set.
For example
NSNumber *myInt = [NSNumber numberWithInteger:100];
float myFloat = [myInt floatValue];
is perfectly valid. NSNumber's strength is that it allows you to "weak-type" your primitives, use compare:, use isEqualTo:, and stringValue for easy display.
[EDIT]
User #Dave DeLong says that sub-classing NSNumber is a Bad Idea without much work. Since it's a class cluster (meaning NSNumber is an abstract superclass of a lot of subclasses) you'll have to declare your own storage if you sub-class it. Not recommended, and thanks to Dave for pointing that out.
As an alternative, there is also the NSDecimal struct for representing numerical types. NSDecimal (and its Objective-C class version NSDecimalNumber) lets you represent true decimals and avoid floating point errors, so it tends to be recommended for dealing with things like currency.
The NSDecimal struct can represent numbers as well as a Not a Number state (a potential nil replacement). You can query whether an NSDecimal is not a number using NSDecimalIsNotANumber(), and generate the Not a Number value with the help of an NSDecimalNumber.
NSDecimals are faster to work with than NSDecimalNumbers, and the structs don't bring the same kind of memory management issues that objects do.
However, there isn't an easy way to get values into NSDecimal form without using a temporary NSDecimalNumber. Also, many of the math functions (like trigonometry operations) that are available for simple floating point numbers aren't yet available for NSDecimal. I'd like to write my own functions that add some of these capabilities, but they would require accessing the internal fields of the struct. Apple labels these as private (with the use of an underscore), but they are present in the headers and I'd guess they're unlikely to change in the future.
Update: Dave DeLong wrote a series of functions for performing NSDecimal trigonometry, roots, and other operations. I've tweaked these to provide up to 34 digits of decimal precision, and the code for these functions can be downloaded here. As a warning, this precision comes at a price in terms of performance, but these functions should be fine for fairly infrequent calculations.
I don't understand why, if you store stuff as an NSNumber, you need to care what type it is. NSNumber will choose an appropriate internal representation and then do any necessary conversion depending on what format you ask for its value in.
If you can't tell what type is appropriate from the name of the variable you need to choose better names. e.g.
numberOfChildren = [NSNumber numberWithFloat: 2.5];
is plainly silly.
And for currency values, I definitely recommend using NSDecimalNumber (which is a subclass of NSNumber) but defines base 10 arithmetic operations so you don't have to worry about float rounding.