Reputation: 81
I am new programming and Objective-C in general. Do I declare a struct in the interface and define it in the implementation use a void method ?...
@interface Elements : NSObject {
struct elementZ{
NSString *name;
float molarmass;
}elements[81];
Now that I have declared it..where do I initialize the elements[81] array?
Upvotes: 0
Views: 4598
Reputation: 34655
Do I declare a struct in the interface and define it in the implementation use a void method ?
Yes it is what you think since Objective C is a super set of C. Have a method, that takes no arguments and returns void and initialize the member variables of struct elementz
through elements[81];
. Probably by running a loop from 0 to 80. As an example -
#import <Foundation/NSObject.h>
@interface Fraction: NSObject {
struct myStructure {
int numerator, denominatior;
}objects[10];
}
-(void) print;
-(void) initialize;
@end
@implementation Fraction
-(void) initialize
{
for( int i=0; i<10; ++i )
{
objects[i].numerator = (i+1);
objects[i].denominatior = (i+2);
}
}
-(void) print
{
for( int i=0; i<10; ++i )
{
printf("%d\t%d\n", objects[i].numerator, objects[i].denominatior);
}
}
@end
int main(int argc, char *argv[])
{
Fraction *obj = [[Fraction alloc] init];
[ obj initialize ];
[ obj print ];
[ obj release ];
return 0;
}
Output:
[Switching to process 949]
Running…
1 2
2 3
3 4
4 5
5 6
6 7
7 8
8 9
9 10
10 11
Debugger stopped. Program exited with status value:0.
Hope it helps !
Upvotes: 1
Reputation: 511
Add a init method within the implementation block of your Elements class:
- (id)init {
if (self = [super init]) {
for (int i=0; i<81; i++) {
elements[i].name = "foo";
}
}
return self;
}
maybe some reading is required to get familar to Objective-C: Introduction to The Objective-C Programming Language
Object creation in Objective-C requires two steps:
E.g.:
Elements *e = [[Elements alloc] init];
Upvotes: 0
Reputation: 2835
Your code works as is for me. Then you can access the data in your implementation like so:
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
// Insert code here to initialize your application
elements[2].name = @"hello";
NSLog(elements[2].name);
}
This will print 'hello' to the console.
Upvotes: 1
Reputation: 6734
typedef struct element{
NSString *name;
float molarmass;
}elementZ;
elementZ[81] array;
Upvotes: 0