objective-cnsmutablearrayiterationnsenumerator

Objective-C Iterating through an NSString to get characters


I have this function:

void myFunc(NSString* data) {
    NSMutableArray *instrs = [[NSMutableArray alloc] initWithCapacity:[data length]];
    for (int i=0; i < [data length]; i++) {
        unichar c = [data characterAtIndex:i];
        [instrs addObject:c];
    }
    NSEnumerator *e = [instrs objectEnumerator];
    id inst;
    while (inst = [e nextObject]) {
        NSLog("%i\n", inst);
    }
}

I think it fails at [instrs addObject:c]. It's purpose is to iterate through the hexadecimal numbers of an NSString. What causes this code to fail?


Solution

  • A unichar is not an object; it's an integer type.

    NSMutableArray can only hold objects.

    If you really want to put it into an NSMutableArray, you could wrap the integer value in an NSNumber object: [instrs addObject:[NSNumber numberWithInt:c]];

    But, what's the point of stuffing the values into an array in the first place? You know how to iterate through the string and get the characters, why put them into an array just to iterate through them again?

    Also note that: