[SOLVED] Objective-C and fast-enumeration
Posted: Sat Jun 28, 2008 5:52 am
It's unlikely I'll get an answer here but Objective-C forums are few and far between 
I'm not sure what I'm doing wrong here. My understanding is that my "Chatterbox" class should iterate over all "Chatter" instances it has in its internal array. However, although the compiler (gcc on OS X) doesn't generate any errors or warnings, no iterations occur in the loop. I've even added some straight printf() calls to the loop to double-check.
Talker.h
Chatter.h
Chatterbox.h
Chatter.m
Chatterbox.m
main.m
Any ObjC developers here who can tell me what I'm doing wrong? 
I'm not sure what I'm doing wrong here. My understanding is that my "Chatterbox" class should iterate over all "Chatter" instances it has in its internal array. However, although the compiler (gcc on OS X) doesn't generate any errors or warnings, no iterations occur in the loop. I've even added some straight printf() calls to the loop to double-check.
Talker.h
Code: Select all
#import <Foundation/Foundation.h>
@protocol Talker
- (void) talk;
@end
Code: Select all
#import <Foundation/Foundation.h>
#import "Talker.h"
@interface Chatter : NSObject < Talker > {
NSString *phrase;
}
- (void) setPhrase: (NSString *) phrase;
@end
Code: Select all
#import <Foundation/Foundation.h>
#import "Talker.h"
#import "Chatter.h"
@interface Chatterbox : NSObject < Talker > {
NSMutableArray *chatter;
}
- (void) addChatter: (Chatter *) toSay;
@end
Code: Select all
#import <Foundation/Foundation.h>
#import "Chatter.h"
@implementation Chatter
- (void) setPhrase: (NSString *) newPhrase {
phrase = newPhrase;
}
- (void) talk {
printf("%s\n", [phrase cStringUsingEncoding: NSUTF8StringEncoding]);
}
@end
Code: Select all
#import <Foundation/Foundation.h>
#import "Chatterbox.h"
#import "Chatter.h"
@implementation Chatterbox
- (void) addChatter: (Chatter *) toSay {
[chatter addObject: toSay];
}
- (void) talk {
//Something doesn't work here... it's not iterating
for (Chatter < Talker > *talker in chatter) {
[talker talk];
}
}
@end
Code: Select all
#import <Foundation/Foundation.h>
#import "Chatter.h";
#import "Chatterbox.h"
int main(Void) {
NSAutoreleasePool *autoreleasepool = [[NSAutoreleasePool alloc] init];
Chatterbox *chatterbox = [[Chatterbox alloc] init];
Chatter *c1 = [[Chatter alloc] init];
[c1 setPhrase: @"Hello Melbourne!"];
[chatterbox addChatter: c1];
Chatter *c2 = [[Chatter alloc] init];
[c2 setPhrase: @"Hello Australia!"];
[chatterbox addChatter: c2];
Chatter *c3 = [[Chatter alloc] init];
[c3 setPhrase: @"Hello World!"];
[chatterbox addChatter: c3];
Chatter *c4 = [[Chatter alloc] init];
[c4 setPhrase: @"Hello Universe!"];
[chatterbox addChatter: c4];
[chatterbox talk];
[c1 release];
[c2 release];
[c3 release];
[c4 release];
[autoreleasepool release];
}