Objective-C 关联引用的实例 (59)

#import 

@interface NSArray (Random)

- (id)anyOne;

@end



#import "NSArray+Random.h"
#import 

@implementation NSArray (Random)

static char prevKey; //定义键使用的地址变了

static int random_value(void) {
    static unsigned long rnd = 201008;
    rnd = rnd * 1103515245UL + 12345;
    return (int)((rnd >> 16) & 0x7fff);
}

- (id)anyOne
{
    id item;
    NSUInteger count = [self count];
    if (count == 0)
        return nil;
    if (count == 1)
        item = [self lastObject];
    else {
        id prev = objc_getAssociatedObject(self, &prevKey);
        NSUInteger index = random_value() % count;
        item = [self objectAtIndex:index];
        if (item == prev) {
            if (++index >= count)
                index = 0;
            item = [self objectAtIndex:index];
        }
    }
    objc_setAssociatedObject(self, &prevKey, item, OBJC_ASSOCIATION_RETAIN);
    return item;
}

@end


#import 
#import "NSArray+Random.h"

int main(void)
{
    @autoreleasepool {
        id arr1 = [NSArray arrayWithObjects:@"A", @"B", @"C", @"D", @"E", @"F", @"G", @"H", nil];
        id arr2 = [NSMutableArray arrayWithObjects:@"1", @"2", @"3", @"4", nil];
        for (int i = 5; i < 20; i++) {
            @autoreleasepool {
                printf("%s %s\n",[[arr1 anyOne] UTF8String], [[arr2 anyOne] UTF8String]);
            }
        }
    }
    return 0;
}


Objective-C 关联引用的实例 (59)_第1张图片


你可能感兴趣的:(Objective-C,读书笔记)