简体   繁体   中英

iPhone:How to make an integer array and store values in Obj-C?

I want to know a simple thing, which i couldn't get it is that i want to store 10 values in an integer array dynamically and then i have to check that stored values and compared with the current values whether it is same or not in some other condition. Initially i tried same like C array, int temp[10], but seems to be that is not possible to set and get method, then i tried NSNumber like below,

In AppDelagate file,

    NSMutableArray *reqID;
@property (nonatomic,readwrite) 
NSMutableArray * reqID;

@synthesize reqID;

........................

........................

........................

In Some other file,

int rd = (1+arc4random() % [arr count]);

[myDelegate.reqID addObject:[NSNumber numberWithUnsignedInteger:rd]];

then i need to check,

        for (int i=0; i<10; i++)
    {
        NSUInteger anInt = [[myDelegate.reqID objectAtIndex:i] unsignedIntegerValue];

        if ( anInt==rd )
        {
            rd = (1+arc4random() % [arr count]);
            break;
        }
    }

But it doesn' work as expected, ie array value doesn't give proper value. i don't know how to use integer array in Obj-C and handle it to access later etc.

Could someone please explian me?

First of all, you should declare the property like this:

@property (nonatomic,retain) NSMutableArray * reqID;

Second, you will need to actually create an NSMutableArray somewhere. For example:

myDelegate.reqID = [NSMutableArray arrayWithCapacity:10];

Note that you must use myDelegate.reqID rather than reqID so that the object is retained.

(Personally I would use ordinary C arrays here... )

Edit: remember to do [reqID release] when you've finished with it.

Edit 2: Here's how to do this with C arrays:

In your class, add an instance variable int *reqID . Then declare a property:

@property (nonatomic, assign) int *reqID;

Then to allocate space for your array, do:

myDelegate.reqID = malloc(10 * sizeof(int));

Then to access your array you can use [] syntax:

int a = myDelegate.reqID[i];

Then when you have finished, do:

free(myDelegate.reqID);

As well as the stuff Emil has pointed out,

myDelegate.reqID = [NSMutableArray arrayWithCapacity:10];

doesn't give you an array with 10 slots in it, it gives you an empty array with a hint to the runtime that you are eventually going to put 10 things in it. So, if you run youre loop from 0 to 9 before you have added 10 objects, you'll get an NSRangeException because you'll run off the end of the array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM