Skip to content

Instantly share code, notes, and snippets.

@khacanh
Created May 28, 2013 05:39
Show Gist options
  • Save khacanh/5660683 to your computer and use it in GitHub Desktop.
Save khacanh/5660683 to your computer and use it in GitHub Desktop.
Some extensions to obj-c NSArray class
@implementation NSArray(Ext)
-(NSArray*)subarrayWithSize:(int)returnSize
{
int count = self.count;
if (returnSize >= 0 && returnSize <= count)
{
NSMutableArray *result = [[NSMutableArray alloc] init];
NSMutableArray *indexes = [NSMutableArray arrayWithCapacity:count];
for (int i = 0; i < returnSize; i++)
{
int ri;
do {
ri = arc4random() % count;
} while ([indexes indexOfObjectIdenticalTo:@(ri)] != NSNotFound);
result[i] = self[ri];
[indexes addObject:@(ri)];
}
return result;
} else {
return nil;
}
}
-(id)anyObject
{
return self && self.count > 0 ? self[arc4random() % self.count] : nil;
}
-(NSArray*)reverse
{
NSMutableArray *newArray = self ? [NSMutableArray arrayWithCapacity:self.count] : nil;
for (id obj in [self reverseObjectEnumerator])
{
[newArray addObject:obj];
}
return newArray;
}
-(NSArray*)verifiedObjects:(BOOL(^)(id))verifyingBlock
{
NSMutableArray *newArray = self ? [NSMutableArray array] : nil;
for (id obj in self)
{
if (verifyingBlock(obj))
{
[newArray addObject:obj];
}
}
return newArray;
}
-(BOOL)containsSubArrayEqualsTo:(NSArray*)subArr
{
for (id obj in self)
{
if ([obj isEqualToArray:subArr])
{
return TRUE;
}
}
return FALSE;
}
-(NSArray*)extractArrayWithBlock:(id(^)(id))block
{
NSMutableArray *result = [NSMutableArray array];
for (id obj in self)
{
[result addObject:block(obj)];
}
return result;
}
-(NSString*)joinWith:(NSString*)separator
{
NSMutableString *result = [NSMutableString stringWithString:@""];
for (id obj in self)
{
if (obj == [self lastObject])
{
[result appendFormat:@"%@", [obj description]];
} else {
[result appendFormat:@"%@%@", [obj description], separator];
}
}
return result;
}
-(int)indexOfObjectMeetsCondition:(BOOL(^)(id))block
{
for (int i = 0; i < self.count; i++)
{
id obj = self[i];
if (block(obj))
{
return i;
}
}
return NSNotFound;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment