Skip to content

Instantly share code, notes, and snippets.

@mrtj
Last active July 18, 2018 19:47
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mrtj/4705733 to your computer and use it in GitHub Desktop.
Save mrtj/4705733 to your computer and use it in GitHub Desktop.
Simple Objective C wrapper around a C integer array. Supports fast enumeration via NSNumber objects. #integer #array #objective-c License: BSD
// Author: janos.tolgyesi@gmail.com
// License: BSD
#import <Foundation/Foundation.h>
@interface TJIntegerArray : NSObject <NSFastEnumeration>
{
NSInteger* _array;
}
-(id)initWithCount:(NSUInteger)count;
-(NSInteger)integerAtIndex:(NSUInteger)index;
-(void)setInteger:(NSInteger)value atIndex:(NSUInteger)index;
@property (nonatomic, readonly) NSUInteger count;
@end
// Author: janos.tolgyesi@gmail.com
// License: BSD
#import "TJIntegerArray.h"
@interface TJIntegerArray ()
-(void)checkBounds:(NSUInteger)index;
@end
@implementation TJIntegerArray
@synthesize count = _count;
- (id)init
{
self = [super init];
if (self) {
_count = 0;
_array = 0;
}
return self;
}
- (id)initWithCount:(NSUInteger)count
{
self = [super init];
if (self) {
_count = count;
_array = calloc(count, sizeof(NSInteger));
}
return self;
}
- (void)dealloc
{
free(_array);
#if !__has_feature(objc_arc)
[super dealloc];
#endif
}
-(NSInteger)integerAtIndex:(NSUInteger)index
{
[self checkBounds:index];
return (NSInteger) _array[index];
}
-(void)setInteger:(NSInteger)value atIndex:(NSUInteger)index
{
[self checkBounds:index];
_array[index] = value;
}
-(void)checkBounds:(NSUInteger)index
{
if (index >= _count) {
NSString* message = [NSString stringWithFormat:@"*** %s: index (%d) beyond bounds (%d)",
__PRETTY_FUNCTION__, index, _count];
NSException* rangeException = [NSException exceptionWithName:NSRangeException
reason:message
userInfo:nil];
@throw rangeException;
}
}
#pragma mark - NSFastEnumeration
-(NSUInteger)countByEnumeratingWithState:(NSFastEnumerationState *)state
objects:(__unsafe_unretained id [])buffer
count:(NSUInteger)len
{
NSUInteger count = 0;
if(state->state == 0) state->mutationsPtr = &state->extra[0];
if(state->state < _count)
{
state->itemsPtr = buffer;
while((state->state < _count) && (count < len))
{
buffer[count] = [NSNumber numberWithInteger:_array[state->state]];
state->state++;
count++;
}
}
else
{
count = 0;
}
return count;
}
@end
@paulmelnikow
Copy link

Hi, thanks for posting this. Does this have a license? Public domain or BSD or something?

@mrtj
Copy link
Author

mrtj commented Nov 25, 2015

Hi, I am glad if it's useful for you. Licensing is BSD.

@CoderXXLee
Copy link

很不错哦

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment