Coder Social home page Coder Social logo

objectivesugar's Introduction

logo

Write Objective C like a boss.

A set of functional additions for Foundation you wish you'd had in the first place.

Build Status

Usage

  1. Install via CocoaPods

    pod 'ObjectiveSugar'
    
  2. Import the public header

    #import <ObjectiveSugar/ObjectiveSugar.h>
    

Documentation

NSNumber additions

[@3 times:^{
    NSLog(@"Hello!");
}];
// Hello!
// Hello!
// Hello!

[@3 timesWithIndex:^(NSUInteger index) {
    NSLog(@"Another version with number: %d", index);
}];
// Another version with number: 0
// Another version with number: 1
// Another version with number: 2


[@1 upto:4 do:^(NSInteger numbah) {
    NSLog(@"Current number.. %d", numbah);
}];
// Current number.. 1
// Current number.. 2
// Current number.. 3
// Current number.. 4

[@7 downto:4 do:^(NSInteger numbah) {
    NSLog(@"Current number.. %d", numbah);
}];
// Current number.. 7
// Current number.. 6
// Current number.. 5
// Current number.. 4

NSDate *firstOfDecember = [NSDate date]; // let's pretend it's 1st of December

NSDate *firstOfNovember = [@30.days since:firstOfDecember];
// 2012-11-01 00:00:00 +0000

NSDate *christmas = [@7.days until:newYearsDay];
// 2012-12-25 00:00:00 +0000

NSDate *future = @24.days.fromNow;
// 2012-12-25 20:49:05 +0000

NSDate *past = @1.month.ago;
// 2012-11-01 20:50:28 +00:00

-- NSArray / NSSet additions

// All of these methods return a modified copy of the array.
// They're not modifying the source array.

NSArray *cars = @[@"Testarossa", @"F50", @"F458 Italia"]; // or NSSet

[cars each:^(id object) {
    NSLog(@"Car: %@", object);
}];
// Car: Testarossa
// Car: F50
// Car: F458 Italia

[cars eachWithIndex:^(id object, NSUInteger index) {
    NSLog(@"Car: %@ index: %i", object, index);
}];
// Car: Testarossa index: 0
// Car: F50 index: 1
// Car: F458 Italia index: 2

[cars each:^(id object) {
    NSLog(@"Car: %@", object);
} options:NSEnumerationReverse];
// Car: F458 Italia
// Car: F50
// Car: Testarossa

[cars eachWithIndex:^(id object, NSUInteger index) {
    NSLog(@"Car: %@ index: %i", object, index);
} options:NSEnumerationReverse];
// Car: F458 Italia index: 2
// Car: F50 index: 1
// Car: Testarossa index: 0

[cars map:^(NSString* car) {
    return car.lowercaseString;
}];
// testarossa, f50, f458 italia

// Or, a more common example:
[cars map:^(NSString* carName) {
    return [[Car alloc] initWithName:carName];
}];
// array of Car objects

NSArray *mixedData = @[ @1, @"Objective Sugar!", @"Github", @4, @"5"];

[mixedData select:^BOOL(id object) {
  return ([object class] == [NSString class]);
}];
// Objective Sugar, Github, 5

[mixedData reject:^BOOL(id object) {
    return ([object class] == [NSString class]);
}];
// 1, 4

NSArray *numbers = @[ @5, @2, @7, @1 ];
[numbers sort];
// 1, 2, 5, 7

cars.sample
// 458 Italia
cars.sample
// F50

-- NSArray only

NSArray *numbers = @[@1, @2, @3, @4, @5, @6];

// index from 2 to 4
numbers[@"2..4"];
// [@3, @4, @5]

// index from 2 to 4 (excluded)
numbers[@"2...4"];
// [@3, @4]

// With NSRange location: 2, length: 4
numbers[@"2,4"];
// [@3, @4, @5, @6]

NSValue *range = [NSValue valueWithRange:NSMakeRange(2, 4)];
numbers[range];
// [@3, @4, @5, @6]

[numbers reverse];
// [@6, @5, @4, @3, @2, @1]


NSArray *fruits = @[ @"banana", @"mango", @"apple", @"pear" ];

[fruits includes:@"apple"];
// YES

[fruits take:3];
// banana, mango, apple

[fruits takeWhile:^BOOL(id fruit) {
    return ![fruit isEqualToString:@"apple"];
}];
// banana, mango

NSArray *nestedArray = @[ @[ @1, @2, @3 ], @[ @4, @5, @6, @[ @7, @8 ] ], @9, @10 ];
[nestedArray flatten];
// 1, 2, 3, 4, 5, 6, 7, 8, 9, 10

NSArray *abc = @[ @"a", @"b", @"c" ];
[abc join];
// abc

[abc join:@"-"];
// a-b-c

NSArray *mixedData = @[ @1, @"Objective Sugar!", @"Github", @4, @"5"];

[mixedData detect:^BOOL(id object) {
    return ([object class] == [NSString class]);
}];
// Objective Sugar



// TODO: Make a better / simpler example of this
NSArray *landlockedCountries = @[ @"Bolivia", @"Paraguay", @"Austria", @"Switzerland", @"Hungary" ];
NSArray *europeanCountries = @[ @"France", @"Germany", @"Austria", @"Spain", @"Hungary", @"Poland", @"Switzerland" ];


[landlockedCountries intersectionWithArray:europeanCountries];
// landlockedEuropeanCountries = Austria, Switzerland, Hungary

[landlockedCountries unionWithArray:europeanCountries];
// landlockedOrEuropean = Bolivia, Paraguay, Austria, Switzerland, Hungary, France, Germany, Spain, Poland

[landlockedCountries relativeComplement:europeanCountries];
// nonEuropeanLandlockedCountries = Bolivia, Paraguay

[europeanCountries relativeComplement:landlockedCountries];
// notLandlockedEuropeanCountries = France, Germany, Spain, Poland

[landlockedCountries symmetricDifference:europeanCountries];
// uniqueCountries = Bolivia, Paraguay, France, Germany, Spain, Poland

-- NSMutableArray additions

NSMutableArray *people = @[ @"Alice", @"Benjamin", @"Christopher" ];

[people push:@"Daniel"]; // Alice, Benjamin, Christopher, Daniel

[people pop]; // Daniel
// people = Alice, Benjamin, Christopher

[people pop:2]; // Benjamin, Christopher
// people = Alice

[people concat:@[ @"Evan", @"Frank", @"Gavin" ]];
// people = Alice, Evan, Frank, Gavin

[people keepIf:^BOOL(id object) {
    return [object characterAtIndex:0] == 'E';
}];
// people = Evan

-- NSDictionary additions

NSDictionary *dict = @{ @"one" : @1, @"two" : @2, @"three" : @3 };

[dict each:^(id key, id value){
    NSLog(@"Key: %@, Value: %@", key, value);
}];
// Key: one, Value: 1
// Key: two, Value: 2
// Key: three, Value: 3

[dict eachKey:^(id key) {
    NSLog(@"Key: %@", key);
}];
// Key: one
// Key: two
// Key: three

[dict eachValue:^(id value) {
    NSLog(@"Value: %@", value);
}];
// Value: 1
// Value: 2
// Value: 3

[dict invert];
// { 1 = one, 2 = two, 3 = three}

NSDictionary *errors = @{
    @"username" : @[ @"already taken" ],
    @"password" : @[ @"is too short (minimum is 8 characters)", @"not complex enough" ],
    @"email" : @[ @"can't be blank" ];
};

[errors map:^(id attribute, id reasons) {
    return NSStringWithFormat(@"%@ %@", attribute, [reasons join:@", "]);
}];
// username already taken
// password is too short (minimum is 8 characters), not complex enough
// email can't be blank

[errors hasKey:@"email"]
// true
[errors hasKey:@"Alcatraz"]
// false

-- NSString additions

NSString *sentence = NSStringWithFormat(@"This is a text-with-argument %@", @1234);
// This is a text-with-argument 1234

[sentence split];
// array = this, is, a, text-with-argument, 1234

[sentence split:@"-"]
// array = this is a text, with, argument 1234

[sentence containsString:@"this is a"];
// YES

[sentence match:@"-[a-z]+-"]
// -with-

-- C additions

unless(_messages) {
    // The body is only executed if the condition is false
    _messages = [self initializeMessages];
}

int iterations = 10;
until(iterations == 0) {
    // The body is executed until the condition is false
    // 10 9 8 7 6 5 4 3 2 1
    printf("%d ", iterations);
    iterations--;
}
printf("\n");

iterations = 10;
do {
    // The body is executed at least once until the condition is false
    // Will print: Executed!
    printf("Executed!\n");
} until(true);

Contributing

ObjectiveSugar is tested with Kiwi, and tests are located in Example.
If you plan on contributing to the project, please:

  • Write tests
  • Write documentation

Team

objectivesugar's People

Contributors

alladinian avatar c0deh4cker avatar dasmer avatar fabiopelosin avatar fpotter avatar gurgeous avatar inf0rmer avatar johnno1962 avatar julien-c avatar kam800 avatar kastiglione avatar kattrali avatar kouky avatar matty316 avatar mickeyreiss avatar mrzoidberg avatar nadinengland avatar neilco avatar onevcat avatar orta avatar robinsenior avatar schukin avatar sebastiangrail avatar seivan avatar serheo avatar shkutkov avatar supermarin avatar viking2009 avatar zachwill avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

objectivesugar's Issues

Problem with NSDictionary map

should be fixed with

[self enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
    id object = block(key, obj);
    if (object)
        [array addObject:object];
}];

Add one function : map NSArray and skip someone

Sometimes not only need to map out an array, but also need to conditional mapping. Reference to NSArray's block traversal method - (void) enumerateObjectsUsingBlock: (void (NS_NOESCAPE ^) (ObjectType obj, NSUInteger idx, BOOL * stop)) block.

Add a skip option for the mapping method:

- (NSArray *) mm_mapWithskip:(id (^)(id obj, BOOL *skip))callback{
    
    NSMutableArray * _self = [NSMutableArray arrayWithCapacity:self.count];
    
    for( id obj in self ){
        
        BOOL skip = NO;
        
        id mapObj = callback(obj, &skip);
        
        if( !skip ){
            [_self addObject:mapObj];
        }
    }
    return [_self copy];
}

Refer to this answer

NSArray, NSSet first

methods aren't safe

NSArray

- (id)first {
    return [self objectAtIndex:0];
}

should be

- (id)first {
    if (self.count > 0)
        return [self objectAtIndex:0];
    return nil;
}

NSSet

- (id)first {
    return self.allObjects[0];
}

should be

- (id)first {
    NSArray *allObjects = self.allObjects;
    if (allObjects.count > 0)
        return [allObjects objectAtIndex:0];
    return nil;
}

problem with NSArray map

should be fixed with

for (id object in self) {
    id newObject = block(object);
    if (newObject)
        [array addObject:newObject];
}

Shorter NSStringWithFormat

As you all know, [NSString stringWithFormat:@"...", ...] is a lot of syntax for something so common. This is why ObjectiveSugar implemented the NSStringWithFormat function.
It is indeed shorter, but well... not a lot.

How about a format: method on NSString?
[@"..." format:...] would be much more appealing in my opinion.

I will implement this method and update the tests and doc if anyone finds this useful.

Use fast enumeration

NSArray+ObjectiveSugar.m

  • (void)each:(void (^)(id object))block {
    for (id object in self)
    block(object);
    }

NSDictionary+ObjectiveSugar.m

  • (void)eachKey:(void (^)(id k))block {
    for (id key in self)
    block(key);
    }

NSSet+ObjectiveSugar.m

  • (void)each:(void (^)(id object))block {
    for (id object in self)
    block(object);
    }

NSSet should return NSSet

I've been looking for a replacement for BlocksKit, and I was wondering why NSSet selectors return an NSArray?
And would you be open for a PR to change it?

NSNumber date methods not accounting for DST, leap year and other date/calendar oddities

The current methods can give a fast approximation, but they can cause some inaccurate/misleading results when you factor in things like daylight savings time and leap year. On a day where the clocks were set back for daylight savings time, one would probably expect @(1).day.ago executed at 2pm to return 2pm the previous day, but since 24 hours ago was 3pm the previous day, that's the time you'll get back with the current implementation.

It looks like the SexyDates project handles that correctly. [NSCalendar currentCalendar] is too slow to call repeatedly without cacheing on iOS 6 and lower, but evidently is now cached in iOS 7. If you're concerned about performance on iOS 6, you can cache the NSCalendar in a thread dictionary.

I'd be happy to work on this if you let me know your thoughts on it before I get started.

Problem with NSSet map

should be fixed with

for (id object in self) {
    id newObject = block(object);
    if (newObject)
        [array addObject:newObject];
}

Returning NSMutableArray as NSArray

Hey guys, I see multiple places where the method signature says the return type is NSArray but the actual object being returned is NSMutableArray. This is a potential problem because the returned object will still respond to NSMutableArray messages. It is Apple's recommendation and standard practice to make a non-mutable copy of the array before returning. So:

NSMutableArray *myArray = ...
// fill the array here
return myArray;

should become

NSMutableArray *myArray = ...
// fill the array here
return [myArray copy];

You can also use [NSArray arrayWithArray:myArray] instead of [myArray copy](I think "copy" in this case just makes a call to arrayWithArray anyway, so using arrayWithArray cuts out a directive or two).

RFE: add "all" / "every" method to collections

I miss this simple addition:

 - (BOOL)all:(BOOL (^)(id object))condition;

i.e:

NSArray *list = @['a', 'b', 'c'];
BOOL allMatch = [list all:^(id object) { return id != nil }];
assert( allMatch );

Naming consistency

Why are there +Accessors, +Rubyfy and now +Sweetner categories? Why isn't it NSString+Rubyfy.m? Or even better, why aren't all of them +ObjectiveSugar?

Wonderful project, but it doesn't seem very consistent now.

documentation up to date?

So, how up-to-date is the documentation in the README? Some of the examples don't seem to work (though I may just be an idiot):

//this gives the error "no visibile @interface for 'nsarray' declares the selector 'detect'"

NSArray *mixedData = @[ @1, @"Objective Sugar!", @"Github", @4, @"5"];
[mixedData detect:^BOOL(id object) {
    return ([object class] == [NSString class]);
}];

//this gives the error 'Expected method to read dictionary element not found on object of type 'NSArray *'

NSArray *indices = @[@1, @2, @3, @4, @5];
indices[@"1..3"];

Other examples seem to work, however. Am I missing something?

Macros proposal

Hi,

thanks for starting this library! I was planning to do it myself, but never found the time to. I have experimented with some macros to bring the part of ruby that I love the most to Objective-C. Following you can find the unfinished result. What do you think? Is this something that you would be interested in adding to your ObjectiveSugar?

//#define RACAble(...) metamacro_if_eq(1, metamacro_argcount(__VA_ARGS__))(_RACAbleObject(self, __VA_ARGS__))(_RACAbleObject(__VA_ARGS__))

///-----------------------------------------------------------------------------
// @name map
///-----------------------------------------------------------------------------

#define $to(selector) ^id (id x) { return [x selector]; }
[authors map:$to(name)] 
[authors map:$to(nameWithAge:date)]

///-----------------------------------------------------------------------------
// @name filter & select
///-----------------------------------------------------------------------------

#define $by(selector) ^BOOL (id x) { return [x selector]; }
[views filter:$by(hidden)]

#define $if(expression) ^BOOL (id x) { return (expression); }
[views filter:$if([x frame].origin.x > 10)]


///-----------------------------------------------------------------------------
// @name each
///-----------------------------------------------------------------------------

#define $do(expression) ^(id x) { {expression;}; }
[lions each:$do(attack)]

#define $doWithKey(expression) ^(id* key, id x) { (expression); }

Pod not updated

It seems that when adding the project in a Podfile it does not get updated (getting 1.1.0 version).
Please check.

ld: library not found for -llibPods-test

Every time I pull new updates from this project, I have to modify the test project to get it to build with the error shown in the title of this issue. I'd like to suggest you add the Pods project to the workspace and make it a dependency to the SampleProjectTests target.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.