Trying to grab integer from pre-defined p-list? ObjC/Cocoa - objective-c

I'm working on an Objective-C/Cocoa roguelike, because I've always found that working on a game is the best way to learn about a language. I've gotten quite far with my game, but I'm having a problem.
Each level.plist is defined with a few things, like so:
<key>Save Location</key>
<integer>0</integer>
It's grabbed like so, I'd also like to say that this code is all working fine:
NSObject* level = [mapDictionary_ objectForKey: kLevelNumberKey];
However, in my NSLog-exploring, I've found that instead of grabbing me an integer, or even a useful number, this grabs me an object of some sort, which returns the correct value when NSLogged. How would I go about making this value into an integer so that I can use it like I'd want to be? Note that I've only used NSObject* because nothing else worked right. If I used =(int) instead I would get the pointer value or whatever (1108608 for example).
I'm sure it's a simple solution, and I thank you in advance. If you would not mind explaining exactly what is happening, that would be great. My grasp of the concepts is fine, better than most newcomers, but I'm always interested in exactly what is happening. What use would learning to program be if I didn't know what was going on! Please be more than willing to advise me of other situations like this to watch out/be ready for as well. Any advice, really is appreciated, and will be going to somebody who intends to code for a very long time. I put off learning this much too long, my only regret is not starting earlier.
If, for whatever reason, you are interested in trying out my game so far: Link I'm currently in the process of implementing state-saving so that levels remain as you left them. It's obviously OS X only. I'm pretty proud of it so far, but I have a long ways left. The controls are listed in the app.

The value is an NSNumber object. You can get it as an int using the -intValue method
More details about Property List types

Related

Is it possible for me to set my boolean variable to true and false at the same time?

The program I'm writing, or at least what I have written of it so far, really relies on this somehow working.
If anyone could come up with a direct solution that would be really appreciated, but if it's impossible (or at least really improbable) then I guess a workaround would work, but it would be extremely inconvenient to my work.
That sort of goes against the definition of a boolean.
You could create your own custom structure that can be any of 3 states instead.

Variables vs declarations for simple values

I am not an amateur programmer, but this question surely sounds somewhat amateurish, that may be because I learned programming by experimentation, tutorials, and advice from forums and stackoverflow among other things.
But, I was just thinking while working with some (javascript) code I was making the other day where I realized with simple numbers I was using in part of some algebra equation I had in there - some of them were being used twice, or a few times, and so I had done what I've done in similar situations. That is, I put them into variables representing them, and then using them in the multiple instances they were needed. Although, this might be obvious, something along the lines of this example:
var two = 2;
var seven = 7;
var eighteen = 18;
var calculate = (((seven * 140) / (seven + eighteen)) + ((eighteen * 50) + two) * two);
Now I know this calculation makes no sense, but it's not meant to make any sense, it's just a random calculation I made up to illustrate my point.
But the question I have is is this correct? My logic is why set the same value over and over when I can declare it in a variable and then have it served up from memory rather than repeatedly given. Truthfully this question has been in my mind for quite some time, but I never bothered asking it in risk of looking somewhat stupid, but I just decided I just want to know a definitive answer to it once and for all. For example, I remember having a conversation with somebody a long time ago about this very topic, I don't remember who, maybe it was a teacher in some html class in school, or who knows now. But I remember that person telling me that when it comes to simple values like these, it's best to give the actual value there then having it declared beforehand and calling it from memory, because apparently, this calling and reading of this (or those) variable(s) takes more processing than it would to have it set repeatedly when its needed. Obviously a complex value (like my "calculate" variable) would be better declared before and remembered, but with simple values, this is where I'm not 100% sure.
As I said, this question has been at the back of my mind for quite some time, and I just wanted to know for sure the truth on the matter. I've been using this concept (not frequently, just in rare cases where it becomes necessary) on javascript, jQuery, C#, and T-SQL rarely.
Don't do what you showed in your example. It's good to not have "magic numbers" in code (like 2, 7, and 18), but if you're going to replace them with either macro constants or variables, name them to indicate their purpose. That way, if you have to change a value for some reason, you don't have "two" with a value of 3! "array_stride" with a value of 2 can be changed to value 3 with no confusion.
Now, as to whether or not it's better to put these values in a constant macro literal, or to make variables out of them, that's hard to give a definite answer to. It depends on whether the compiler or whatever can recognize repeated uses of the same constant value, and optimize it to only allocate one piece of storage for it. If it can, it really doesn't matter which you do, as it will store the value in one place and load it wherever needed (with sufficient registers, you might get it kept in a register, which would load faster). If it can't, you'd be better off making a variable. So, perhaps it would be better to have a full-fledged variable.

How can i make my code "save against concurrent invocations" when using "NSSortConcurrent" in sortedArrayWithOptions:usingComparator?

Im trying to sort an Array of NSDates using the sortedArrayWithOptions:usingComparator: - method od NSArray. So far all is very well and my code works as expected.
However, seeing that i can specify options for the method to use, i went into the docs and tried to figure out what they mean.
Theres NSSortStable, of course: Objects that have the same Value should be returned in the order they existed in before the sort. Thats easy enough, i guess.
But im somewhat stumped as to what NSSortConcurrent means. This is what the docs say:
Specifies that the Block sort operation should be concurrent.
This option is a hint and may be ignored by the implementation under some circumstances;
the code of the Block must be safe against concurrent invocation.
Available in Mac OS X v10.6 and later.
So i understand that i can allow the use of multiple threads for the sorting operation? thats great. In this case, is "save against concurrent invocations" just fancy talk for "thread-safe"? And if it isnt, what does it mean? Im sorry for this rather stupid question, but im not a native english speaker. Thanks.
Never mind, i figured ot out. NSSortConcurrent will indeed allow the sorting operation to use multiple threads, and thus the only rewuirement is for the sorting block to be thread-safe. As long as youre not touching any data that is located outside the block (so dont use __block-variables) you should be fine.

Handling lots of objects

First, I am an objective-c newbie. Just thought I would get that out of the way ;)
I am trying to handle objects but I'm a bit confused about the best way to go around doing so. Let me put this into a bit of context:
I have a preference area where a user can add a new Foo to the app. Once the input fields are validated it should spawn a new object of type Foo (according to my Foo class). The user could have anywhere from 1 to 100 of these in the app. What is the best way of keeping track of all of these? How can I create them in the code and keep track of them?
I bet that made no sense, but I have tried to explain it the best I can. Please feel free to ask for more details.
Thanks in advance for any help
Oh, I thought you said lots. :-) I was already planning an explanation on the flyweight pattern when I read 'up to 100'. You can just put these in an array.
It depends somewhat on what you want to do with them. To just keep them in RAM, you can store pointers to those objects in an NSArray (or NSMutableArray), or if you need to be able to find them with a key use an NSDictionary (or NSMutableDictionary). To save them so that they persist even after your app exits so you can load them again next time you can them write them to a file (plist, sqllite, coredata, ...).

Good Use Cases of Comments

I've always hated comments that fill half the screen with asterisks just to tell you that the function returns a string, I never read those comments.
However, I do read comments that describe why something is done and how it's done (usually the single line comments in the code); those come in really handy when trying to understand someone else's code.
But when it comes to writing comments, I don't write that, rather, I use comments only when writing algorithms in programming contests, I'd think of how the algorithm will do what it does then I'd write each one in a comment, then write the code that corresponds to that comment.
An example would be:
//loop though all the names from n to j - 1
Other than that I can't imagine why anyone would waste valuable time writing comments when he could be writing code.
Am I right or wrong? Am I missing something? What other good use cases of comments am I not aware of?
Comments should express why you are doing something not what you are doing
It's an old adage, but a good metric to use is:
Comment why you're doing something, not how you're doing it.
Saying "loop through all the names from n to j-1" should be immediately clear to even a novice programmer from the code alone. Giving the reason why you're doing that can help with readability.
If you use something like Doxygen, you can fully document your return types, arguments, etc. and generate a nice "source code manual." I often do this for clients so that the team that inherits my code isn't entirely lost (or forced to review every header).
Documentation blocks are often overdone, especially is strongly typed languages. It makes a lot more sense to be verbose with something like Python or PHP than C++ or Java. That said, it's still nice to do for methods & members that aren't self explanatory (not named update, for instance).
I've been saved many hours of thinking, simply by commenting what I'd want to tell myself if I were reading my code for the first time. More narrative and less observation. Comments should not only help others, but yourself as well... especially if you haven't touched it in five years. I have some ten year old Perl that I wrote and I still don't know what it does anymore.
Something very dirty, that I've done in PHP & Python, is use reflection to retrieve comment blocks and label elements in the user interface. It's a use case, albeit nasty.
If using a bug tracker, I'll also drop the bug ID near my changes, so that I have a reference back to the tracker. This is in addition to a brief description of the change (inline change logs).
I also violate the "only comment why not what" rule when I'm doing something that my colleagues rarely see... or when subtlety is important. For instance:
for (int i = 50; i--; ) cout << i; // looping from 49..0 in reverse
for (int i = 50; --i; ) cout << i; // looping from 49..1 in reverse
I use comments in the following situations:
High-level API documentation comments, i.e. what is this class or function for?
Commenting the "why".
A short, high-level summary of what a much longer block of code does. The key word here is summary. If someone wants more detail, the code should be clear enough that they can get it from the code. The point here is to make it easy for someone browsing the code to figure out where some piece of logic is without having to wade through the details of how it's performed. Ideally these cases should be factored out into separate functions instead, but sometimes it's just not do-able because the function would have 15 parameters and/or not be nameable.
Pointing out subtleties that are visible from reading the code if you're really paying attention, but don't stand out as much as they should given their importance.
When I have a good reason why I need to do something in a hackish way (performance, etc.) and can't write the code more clearly instead of using a comment.
Comment everything that you think is not straightforward and you won't be able to understand the next time you see your code.
It's not a bad idea to record what you think your code should be achieving (especially if the code is non-intuitive, if you want to keep comments down to a minimum) so that someone reading it a later date, has an easier time when debugging/bugfixing. Although one of the most frustrating things to encounter in reading someone else's code is cases where the code has been updated, but not the comments....
I've always hated comments that fill half the screen with asterisks just to tell you that the function returns a string, I never read those comments.
Some comments in that vein, not usually with formatting that extreme, actually exist to help tools like JavaDoc and Doxygen generate documentation for your code. This, I think, is a good form of comment, because it has both a human- and machine-readable format for documentation (so the machine can translate it to other, more useful formats like HTML), puts the documentation close to the code that it documents (so that if the code changes, the documentation is more likely to be updated to reflect these changes), and generally gives a good (and immediate) explanation to someone new to a large codebase of why a particular function exists.
Otherwise, I agree with everything else that's been stated. Comment why, and only comment when it's not obvious. Other than Doxygen comments, my code generally has very few comments.
Another type of comment that is generally useless is:
// Commented out by Lumpy Cheetosian on 1/17/2009
...uh, OK, the source control system would have told me that. What it won't tell me is WHY Lumpy commented out this seemingly necessary piece of code. Since Lumpy is located in Elbonia, I won't be able to find out until Monday when they all return from the Snerkrumph holiday festival.
Consider your audience, and keep the noise level down. If your comments include too much irrelevant crap, developers will just ignore them in practice.
BTW: Javadoc (or Doxygen, or equiv.) is a Good Thing(tm), IMHO.
I also use comments to document where a specific requirement came from. That way the developer later can look at the requirement that caused the code to be like it was and, if the new requirement conflicts with the other requirment get that resolved before breaking an existing process. Where I work requirments can often come from different groups of people who may not be aware of other requirements then system must meet. We also get frequently asked why we are doing a certain thing a certain way for a particular client and it helps to be able to research to know what requests in our tracking system caused the code to be the way it is. This can also be done on saving the code in the source contol system, but I consider those notes to be comments as well.
Reminds me of
Real programmers don't write documentation
I wrote this comment a while ago, and it's saved me hours since:
// NOTE: the close-bracket above is NOT the class Items.
// There are multiple classes in this file.
// I've already wasted lots of time wondering,
// "why does this new method I added at the end of the class not exist?".