Created
July 20, 2012 12:33
-
-
Save mantognini/3150496 to your computer and use it in GitHub Desktop.
how to use nsarray
This file contains hidden or 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
| #import <Foundation/Foundation.h> | |
| @interface Person : NSObject | |
| @property (nonatomic, strong) NSString *name; | |
| + (id)personWithName:(NSString *)name; | |
| - (id)initWithName:(NSString *)name; | |
| - (void)hello; | |
| @end | |
| @implementation Person | |
| @synthesize name = _name; | |
| + (id)personWithName:(NSString *)name | |
| { | |
| return [[Person alloc] initWithName:name]; | |
| } | |
| - (id)initWithName:(NSString *)name | |
| { | |
| if (self = [super init]) { | |
| self.name = name; | |
| } | |
| return self; | |
| } | |
| - (void)hello | |
| { | |
| NSLog(@"%@ says hello", self.name); | |
| } | |
| @end | |
| int main(int argc, const char * argv[]) | |
| { | |
| @autoreleasepool { | |
| NSArray *array = [NSArray arrayWithObjects:[Person personWithName:@"Bob"], | |
| [Person personWithName:@"John"], nil]; | |
| { | |
| // Solution one : classic for loop | |
| for (NSUInteger index = 0; index < [array count]; ++index) { | |
| Person *p = [array objectAtIndex:index]; | |
| [p hello]; | |
| } | |
| } | |
| { | |
| // Solution two : forin loop | |
| for (Person *p in array) { | |
| [p hello]; | |
| } | |
| } | |
| { | |
| // Solution three : enumeration with block | |
| [array enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { | |
| Person *p = obj; | |
| [p hello]; | |
| }]; | |
| } | |
| { | |
| // Solution three bis (be causious while changing the type! it's not safe) | |
| [array enumerateObjectsUsingBlock:^(Person *p, NSUInteger idx, BOOL *stop) { | |
| [p hello]; | |
| }]; | |
| } | |
| { | |
| // Solution four : NSEnumerator | |
| NSEnumerator *enumerator = [array objectEnumerator]; | |
| Person *p = nil; | |
| while (p = [enumerator nextObject]) { | |
| [p hello]; | |
| } | |
| } | |
| } | |
| return 0; | |
| } |
Author
Test
Author
test
Author
test
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
this is comment test