Domanda

I just started learning objective-c and I'm trying to use a random number to get the value for the key of that number.

Obviously (for most of you) this won't compile since NSNumber and NSUInteger are of different data type. But this was my best shot but the compiler gives me the following error:

Implicit conversion of a non-Objective-C pointer type 'NSUInteger *' (aka 'unsigned int *') to 'id' is disallowed with ARC

Is there anyone out there, willing to guide me to this probably trivial (for plenty of you) issue?

This is my attempt:

NSDictionary *refDictionary = [[NSDictionary alloc] initWithObjectsAndKeys:
                                    @"one", [NSNumber numberWithInteger:0],
                                    @"two", [NSNumber numberWithInteger:1],
                                    @"one", [NSNumber numberWithInteger:2],
                                    @"two", [NSNumber numberWithInteger:3],
                                    @"four",[NSNumber numberWithInteger:4],
                                    @"six", [NSNumber numberWithInteger:5], nil];


        NSUInteger *dieIndex = arc4random_uniform(6);

        NSString *imageName = [refDictionary objectForKey:dieIndex];
È stato utile?

Soluzione

You can use:

[NSNumber numberWithUnsignedInteger:dieIndex]

 NSString *imageName = [refDictionary objectForKey: [NSNumber  numberWithUnsignedInteger:dieIndex]  ];

Altri suggerimenti

Two problems:

  1. You didn't #import <stdlib.h>, so the compiler doesn't know where to find the arc4random_uniform() function — and worse, your code implies the wrong signature for it. It returns u_int32_t, not NSUInteger*.

  2. You should be using the same syntax to convert numbers to NSNumber that you already know how to use:

    int dieIndex = arc4random_uniform(6);
    
    NSString *imageName = [refDictionary objectForKey:[NSNumber numberWithInteger:dieIndex]];
    

If you want to make your code more readable (and non-portable to older versions of iOS), you can even use new-style syntax:

    NSString *imageName = refDictionary[@(dieIndex)];
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top