objc中的容器都分为 non-mutable、mutable 两大类。
看看简单的 array 怎么用。
--------------------------------------------
#include <Foundation/Foundation.h>
@interface God : NSObject {
}
- (void) printMe;
@end
@implementation God
- (void) printMe
{
NSLog(@"print: %@", [self description]);
}
@end
@interface Foo : God {
}
- (NSString *) description;
@end
@implementation Foo
- (NSString *) description
{
return @"I'm foo.";
}
@end
@interface Bar : God {
}
- (NSString *) description;
@end
@implementation Bar
- (NSString *) description
{
return @"I'm bar.";
}
@end
int main()
{
int i;
NSNumber *a = [NSNumber numberWithInt:10];
NSNumber *b = [NSNumber numberWithFloat:2.5];
NSString *c = @"hello";
NSArray *arr = [NSArray arrayWithObjects:a, b, c, nil];
for ( i = 0; i < [arr count]; i++ )
{
NSLog(@"#%d = %@", i, [arr objectAtIndex:i]);
}
NSLog(@"last = %@", [arr lastObject]);
Foo *t1 = [[Foo alloc] init];
Bar *t2 = [[Bar alloc] init];
NSArray *arr2 = [NSArray arrayWithObjects:t1,t2,nil];
for ( i = 0; i < [arr2 count]; i++ )
{
NSLog(@"#%d = %@", i, [arr2 objectAtIndex:i]); // 自动调用 description()
}
SEL func1 = @selector(printMe);
[arr2 makeObjectsPerformSelector:func1]; // 调用所有元素的func1函数
NSMutableArray *arr3 = [NSMutableArray arrayWithObjects:[NSNumber numberWithInt:1],nil];
[arr3 addObject:[NSNumber numberWithInt:2]]; // insert at last
[arr3 insertObject:[NSNumber numberWithInt:3] atIndex:1]; // insert at somewhere
for ( i = 0; i < [arr3 count]; i++ )
{
NSLog(@"#%d = %@", i, [arr3 objectAtIndex:i]);
}
[arr3 removeObjectAtIndex:1];
return 0;
}
--------------------------------------------
评论