Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add string objects to NSMutableArray

I have an NSMutableArray named randomSelection:

NSMutableArray *randomSelection; 

I am then trying to add strings to this array if certain criteria are met:

[randomSelection addObject:@"string1"]; 

I am then trying to output the string, to determine if it has added it:

NSString *test = [randomSelection objectAtIndex:0]; NSLog(test); 

However nothing is being output to the error log and I can't figure out why.

Any help/hints appreciated.

like image 377
SamBo Avatar asked Dec 12 '12 06:12

SamBo


People also ask

How to add object in NSMutableArray in Objective C?

NSMutableArray *listData = [[NSMutableArray alloc] initWithContentsOfFile:*filepath*]; // listData = null if the input file does not exist. NSString *jobName = [NSString stringWithFormat:@"My New Job"]; [listData addObject:jobName];

What is difference between NSArray and NSMutableArray?

The primary difference between NSArray and NSMutableArray is that a mutable array can be changed/modified after it has been allocated and initialized, whereas an immutable array, NSArray , cannot.

What is NSMutableArray Objective C?

The NSMutableArray class declares the programmatic interface to objects that manage a modifiable array of objects. This class adds insertion and deletion operations to the basic array-handling behavior inherited from NSArray . NSMutableArray is “toll-free bridged” with its Core Foundation counterpart, CFMutableArray .

What is NSArray?

An object representing a static ordered collection, for use instead of an Array constant in cases that require reference semantics.


2 Answers

I think you are missing to allocate the memory for array. So try this

NSMutableArray *randomSelection = [[NSMutableArray alloc] init]; [randomSelection addObject:@"string1"]; NSString *test = [randomSelection objectAtIndex:0]; NSLog(test); 
like image 200
hp iOS Coder Avatar answered Sep 22 '22 00:09

hp iOS Coder


NSMutableArray *randomSelection =  [[NSMutableArray alloc]init]; [randomSelection addObject:@"string1"]; 

You need to alloc it first.

like image 43
Pratik Mistry Avatar answered Sep 22 '22 00:09

Pratik Mistry