Created
August 31, 2013 11:03
-
-
Save Shilo/6397570 to your computer and use it in GitHub Desktop.
NSString category for string splitting with a limit.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// NSString+ComponentsLimit.h | |
// | |
// Created by Shilo White on 8/31/13. | |
// Copyright (c) 2013 Shilocity Productions. All rights reserved. | |
// | |
#import <Foundation/Foundation.h> | |
@interface NSString (ComponentsLimit) | |
- (NSArray *)componentsSeparatedByString:(NSString *)separator limit:(NSUInteger)limit; | |
@end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// NSString+ComponentsLimit.m | |
// | |
// Created by Shilo White on 8/31/13. | |
// Copyright (c) 2013 Shilocity Productions. All rights reserved. | |
// | |
#import "NSString+ComponentsLimit.h" | |
@implementation NSString (ComponentsLimit) | |
- (NSArray *)componentsSeparatedByString:(NSString *)separator limit:(NSUInteger)limit | |
{ | |
if (limit == 0) | |
return [self componentsSeparatedByString:separator]; | |
NSArray *allComponents = [self componentsSeparatedByString:separator]; | |
NSMutableArray *components = [NSMutableArray arrayWithCapacity:MIN(limit, allComponents.count)]; | |
int i = 0; | |
for (NSString *component in allComponents) | |
{ | |
if (i >= limit) | |
{ | |
[components addObject:[[allComponents subarrayWithRange:NSMakeRange(i, allComponents.count-1)] componentsJoinedByString:separator]]; | |
break; | |
} | |
[components addObject:component]; | |
i++; | |
} | |
return components; | |
} | |
@end |
Thank you! Unfortunately this code is very old and I no longer use Objective-C as well as have no time. So I can not validate any of it. I will take your word for it, thank you for the effort and contribution!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This doesn't work at all and crashes because:
allComponents.count-1
butallComponents.count-i
i >= limit
butlimit - 1
Implementation that works: