Skip to content

Instantly share code, notes, and snippets.

@mantognini
Created July 20, 2012 12:33
Show Gist options
  • Select an option

  • Save mantognini/3150496 to your computer and use it in GitHub Desktop.

Select an option

Save mantognini/3150496 to your computer and use it in GitHub Desktop.
how to use nsarray
#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;
}
@mantognini
Copy link
Author

this is comment test

@petros
Copy link

petros commented Oct 8, 2012

Test

@mantognini
Copy link
Author

test

@mantognini
Copy link
Author

test

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