Note that there are some explanatory texts on larger screens.

plurals
  1. POHow can I prevent myself from accidentally using an NSNumber's pointer when I want its intValue?
    primarykey
    data
    text
    <p>One feature of Java that I really like is autoboxing, in which the compiler automatically converts between primitives and their wrapper classes.</p> <p>I'm writing a Core Data application in Objective-C/Cocoa, and I'm finding it frustrating to deal with my integer attributes programmatically. Here's why:</p> <pre><code>//img is a managed object that I have fetched NSString* filename = [NSString stringWithFormat:@"image%d.png", [[img valueForKey:@"imageID"] intValue]]; </code></pre> <p>If I happen to forget the <code>intValue</code> message, which I sometimes do, then the int that gets passed to <code>stringWithFormat:</code> is actually the pointer value.</p> <p>The problem is that this happens totally silently--no compiler error or warning. Sometimes I'll spend way too long debugging when this silly, stupid thing is the problem.</p> <p>Is there a way to change my programming style or my compiler settings to prevent me from getting caught in that trap?</p> <p><strong>Edit</strong>: I wasn't clear about the fact that the above example is just one of many places where I run into trouble. Here's another hypothetical example that doesn't have to do with strings:</p> <p>Entity <code>CollegeClass</code> has two integer attributes: <code>courseNumber</code> and <code>enrollmentLimit</code>. Let's say I want to compare course numbers:</p> <pre><code>//classFoo is a NSManagedObjects I've fetched if ([[classFoo valueForKey@"courseNumber"] intValue] &lt; 400) { NSLog(@"undergraduate class"); } </code></pre> <p>Or similarly, suppose I want to compute the average enrollment limit for all the classes in the CS department.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload