0

I am trying to store an NSString variable in an NSMutableArray:

@property(weak,nonatomic) NSMutableArray * stringLines;
//----
NSString * string=@"hello";
[self.stringLines addObject: string];

int i=0;
for (id obj in _stringLines){
NSLog(@"printing labels: index %x word %@",i, obj);
i++;
}

but when I try to print the mutable array, it shows me null values. I don't want to assign the text directly to the array, it has to be through the variable string.

Hasan Moh
  • 19
  • 3

3 Answers3

1

Did you initialize self.stringLines? It may be nil. Try initializing to an empty array, then add the strings.

@property(weak,nonatomic) NSMutableArray * stringLines;
//----

self.stringLines = [NSMutableArray array];
NSString *string = @"hello";
[self.stringLines addObject:string];
NSLog(@"Print strings array: %@", self.stringLines);
keithbhunter
  • 12,258
  • 4
  • 33
  • 58
0

That's because you have not allocated the array object. So if you add anything to a nil object you won't find anything inside it. Use this code

//----
self.stringLines = [[NSMutableArray alloc] init];
NSString * string=@"hello";
[self.stringLines addObject: string];
Gandalf
  • 2,399
  • 2
  • 15
  • 19
0

you can also initialize the array by adding the object with literal, so you need only 1 line of code instead of 3:

self.stringLines = @[@"hello"];
thorb65
  • 2,696
  • 2
  • 27
  • 37