You can of course use C-style arrays in Objective-C. I do that with constant arrays, where I build them at compile time and don't modify the contents, similar to the example you showed. You can put constant pointers to objects in them, of which the most likely, or maybe only, kind is NSString*
I also sometimes will use an NSArray or NSDictionary for the same purpose. I'll have an accessor that builds the NSArray/NSDictionary lazily. These objects have some advantages over C-style arrays.
Pitfall here again... Armed with the comment that it should work I made some progress. I was trying to init the constant array in the interface declaration where I establish my globals. It doesn't let me populate the array there.
On the other hand, the C syntax works perfectly inside the implementation declaration, when used locally within a method.
I could use NSArray, but it seemed overkill to alloc a memory region, initWithObjects, and then have to purge - all to make a 10 byte table.
I guess it makes sense that Objective C won't let me embed a code-like construct in the declaration area. But being new to the language that didn't jump out at me.
A constant C-style array needs to be a file scope static or a function local variable. Normally a file scope static would be the way to do this. The static initialization can't go in a class declaration.
I wouldn't worry about overkill in generating an NSArray, unless you have proof that this will be a problem. Your most precious resource is your time. Development time spent tracking down bugs in use of C-Style arrays is wasted if those bugs can't exist if you use an NSArray.
// in your .h
@interface MyListClass : NSObject {
NSArray *list;
}
@property (nonatomic, retain) NSArray *list;
// in your .m
@synthesize list;
- (void) dealloc {[list release];
[super dealloc];
}
// whereever you set it up ( init most likely ):
NSArray *temp = [[NSArray alloc] initWithObjects:[NSNumber numberWithInt:1], [NSNumber numberWithInt:2], [NSNumber numberWithInt:3], nil];
self.list = temp;
[temp release];
There is no need to create an array of NSNumber objects if you only want integer values.
Code:
// in your .h
@interface MyListClass : NSObject {
const int *list;
}
@end
// in your .m
@implementation MyListClass
static const int constList[5] = {1, 2, 3, 4, 5};
...and in init:
list = constList;
@end
Last edited by MobileGeorge; 01-12-2010 at 09:13 PM.
I had a similar problem as I am new to Objective-C. As others are saying, it is the same as the normal C but one difference. That is, you can use them as you expect, but not with Objective-C specific things.
I figured out that C variable initializers can be used in the class interface, too, but not between @interface and the {...} or within the "{...}".
Otherwise they can be declared as you do with normal C header files. They can be also declared outside the block surrounded by an @interface and the paring @end.
E.g. This is OK and the emptyCoordinate can be used in the @implementation: