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

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 ;


@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] ;
        [mutableSet addIndex:index] ;

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


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

@interface NSMutableIndexSet (oneTime)
//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.


#import "NSMutableIndexSet+oneTime.h"

@implementation NSMutableIndexSet (oneTime)
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 of NSIndexSet indexLessThanOrEqualToIndex example article.