Monday, June 17, 2013

NSIndexSet indexLessThanOrEqualToIndex example in Objective C (iOS).


NSIndexSet indexLessThanOrEqualToIndex

Returns either the closest index in the index set that is less than or equal to a specific index or the not-found indicator.

- (NSUInteger)indexLessThanOrEqualToIndex:(NSUInteger)index

Parameters
index
Index being inquired about.

Return Value of [NSIndexSet indexLessThanOrEqualToIndex]
Closest index in the index set less than or equal to index; NSNotFound when the index set contains no qualifying index.

NSIndexSet indexLessThanOrEqualToIndex example.
@interface IKImageBrowserView (event)

- (void)mouseDown:(NSEvent *)theEvent ;

@end

@implementation IKImageBrowserView (event)

- (void)mouseDown:(NSEvent *)theEvent
{
    NSPoint pt = [self convertPoint: theEvent.locationInWindow fromView: nil];

    NSInteger index = [self indexOfItemAtPoint:pt] ;

    if ( index != NSNotFound )
    {
    NSUInteger ge ;
    NSUInteger le ;
    NSIndexSet* set = [self selectionIndexes] ;
    NSMutableIndexSet* mutableSet = [[NSMutableIndexSet alloc] init] ;

    [mutableSet addIndexes:set] ;

    ge = [mutableSet indexGreaterThanOrEqualToIndex:index] ;
    le = [mutableSet indexLessThanOrEqualToIndex:index] ;

    if ( (ge == le) && (ge != NSNotFound) )
    {
        [mutableSet removeIndex:index] ;
    }
    else
    {
        [mutableSet addIndex:index] ;
    }

    [self setSelectionIndexes:mutableSet byExtendingSelection:NO] ;
//      [ mutableSet release ];
    }
}

@end

Example of [NSIndexSet indexLessThanOrEqualToIndex].
#import <Foundation/Foundation.h>

@interface NSMutableIndexSet (oneTime)
-(NSUInteger)oneTimeRandomIndex;
//returns one index from set at random, removing the index from the set so that it won't be returned again.
//As the index set is mutable indexes maybe re-added to the set to become re-eligsble for return by this method.
//Will return NSNotFound if NSMutableIndexSet is empty.
@end

NSMutableIndexSet+oneTime.m

#import "NSMutableIndexSet+oneTime.h"

@implementation NSMutableIndexSet (oneTime)
-(NSUInteger)oneTimeRandomIndex
{
if (self.count < 1)
{
return NSNotFound;
}
NSUInteger x = [self lastIndex];
x = arc4random() % x;
x = [self indexLessThanOrEqualToIndex:x];
if (x == NSNotFound)
{
x = [self indexLessThanOrEqualToIndex:x];
}
[self removeIndex:x];
return x;
}

@end

End of NSIndexSet indexLessThanOrEqualToIndex example article.