Reputation: 21
I have a little (maybe) very simple question that tears my brain appart.
I created a class "ArrayClass":
// ArrayClass.m
#import "ArrayClass.h"
@implementation ArrayClass{
NSMutableArray *NameList;
}
@end
Now I want to fill this array over an object of this class in my main file.
I thought this would be right, but unfortunately got no outcome.
//Main File:
//Create an object
ArrayClass *object_bla = [[ArrayClass alloc] init];
So how can I fill my Array with the "object_bla" object?
I can't get access to this array. With normal e.g. int variables I have no problems.
Actually I'm not futher then yesterday. So that's what I'm trying to do.
I need a class, in wich I create an array. This is because I want later fill this array with some userinput.
So I got my Class:
AClass.h
#import <Foundation/Foundation.h>
@interface AClass : NSObject
//Array deklarieren
@property NSMutableArray *WordList;
@end
No in the main file I want to create an object of this class, to get access to the *WordList Array. Later the class gets more stuff, so thats a tryout right now. I'm a C++ developer and very new to objective-c, so appologize my noob questions pls.
Thats what I'm done so far:
#import <Foundation/Foundation.h>
#import "AClass.h"
int main(int argc, const char * argv[])
{
@autoreleasepool {
//create object
AClass *blabla = [[AClass alloc] init];
//fill array
[blabla.WordList addObject:@"GünterKörper"];
//output
for (int i = 0; i<[blabla.WordList count]; i++){
NSLog(@"Objekte: %@", [blabla.WordList objectAtIndex:i]);
}
}
return 0;
}
But that gives me nothing. The array is empty. What I'm missing here?
Greets
Upvotes: 0
Views: 115
Reputation: 5601
You need to instantiate the array before you can add objects to it. This can be done in various ways:
1 - In the init method of your custom class:
@implementation AClass
- (id)init {
self = [super init];
if (self) {
_WordList = [[NSMutableArray alloc] init];
}
return self
}
// Rest of class implementation...
@end
2 - Use lazy loading by implementing your own property getter in your custom class.
@implementation AClass
- (NSMutableArray *)WordList {
if (_WordList == nil) {
_WordList = [[NSMutableArray alloc] init];
}
return _WordList;
}
// Rest of class implementation...
@end
The second is probably preferred as it only allocates the memory when you actually reference the object.
Upvotes: 0
Reputation: 46543
You need to create an property
for NameList
.
@property (strong) NSMutableArray *NameList;
Then in your main
file
Create a tempArray
in main, fill it with some array, then use:
NSMutableArray *tempArray=[NSMutableArray arrayWithArray:@[@"A",@"B",@"C"]];
[object_bla setNameList:tempArray;
If you want to add one object at a time:
[object_bla.NameList addObject:@"new object"];
Upvotes: 1