0

私はこの機能を持っています:

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);
    }
}

で失敗すると思います[instrs addObject:c]。その目的は、NSString の 16 進数を反復処理することです。このコードが失敗する原因は何ですか?

4

2 に答える 2

5

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:

  • the "%i" NSLog format expects an integer; you can't pass it an object
  • for hexadecimal output, you want "%x", not "%i"
于 2010-10-28T03:21:22.323 に答える
1

関数が文字を16進値として表示することだけを目的としている場合は、次を使用できます。

void myFunc(NSString* data)
{
    NSUInteger len = [data length];
    unichar *buffer = calloc(len, sizeof(unichar));

    if (!buffer) return;

    [data getCharacters:buffer range:NSMakeRange(0, len)];

    for (NSUInteger i = 0; i < len; i++)
        NSLog(@"%04x", (unsigned) buffer[i]);

    free(buffer);
}

これは、アプローチよりも少し効率的です(また、アプローチでreleaseinstrsアレイを使用しないため、ガベージコレクションされていない環境でリークします)。

文字列に16進数が含まれている場合は、が返されるまでNSScanner'sメソッドを繰り返し使用する必要があります。scanHexInt:NO

void myFunc(NSString* data)
{
    NSScanner *scanner = [[NSScanner alloc] initWithString:data];

    unsigned number;

    while ([scanner scanHexInt:&number])
        NSLog(@"%u", number);

    [scanner release];
}
于 2010-10-28T05:45:19.627 に答える