Objective c add string object to an array - iphone

I've looked everywhere for this, online, on stack overflow and cannot still work out what I'm doing wrong.
I'm trying to add an element to an existing NSMutableArray. But it crashes on line 4:
-[__NSArrayI addObject:]: unrecognized selector sent to instance 0x897b320
The code:
NSMutableArray *mystr = [[NSMutableArray alloc] init];
mystr = [NSArray arrayWithObjects:#"hello",#"world",#"etc",nil];
NSString *obj = #"hiagain";
[mystr addObject:obj];
What am I doing wrong? This is driving me crazy!!!

You array is not mutable!. Use NSMutableArray
mystr = [NSMutableArray arrayWithObjects:#"hello",#"world",#"etc",nil];
You get unrecognized selector since NSArray does not contain the addObject method

Your code should be:
NSMutableArray *mystr = [[NSMutableArray alloc] initWithObjects:#"hello",#"world",#"etc",nil];
NSString *obj = #"hiagain";
[mystr addObject:obj];

The second line you're reassigning an instance of NSArray rather of NSMutableArray to your mystr variable.
Try something like this:
NSMutableArray *mystr = [NSMutableArray arrayWithObjects:#"hello",#"world",#"etc",nil];
[mystr addObject:#"hiagain"]

You originally create mystr as a mutable array, but then assign it to a standard NSArray in the next line. Instead of calling "arrayWithObjects," add each item using "addObjects" or some other function that doesn't create a new immutable array.

Ahhhhh spotted it already
Line 2 should be:
[NSMutableArray arrayWithObjects:#"hello",#"world",#"etc",nil];
Sorry to waste your time with that!

Related

how to add object at specified index in NSMutable array?

How can I add object at specified index?
in my problem
NSMutableArray *substring
contains index and object alternatively
and I need to add it to the another array str according to index I getting from this array.
NSMutableArray *str=[NSMutableArray new];
if ([substrings containsObject:#"Category-Sequence:"])
{
NSString *index=[substrings objectAtIndex:5];
//[substrings objectAtIndex:5]
gives me integer position at which I need to add object in `str` array,
gives 5,4,8,2,7,1 etc
NSString *object=[substrings objectAtIndex:1];
//[substrings objectAtIndex:1] gives object,gives NSString type of object
[str insertObject:object atIndex:(index.intValue)];
}
please suggest some way to achieve it.
Thanks in advance!
Allocate the array first & then try to add objects in it.
NSMutableArray *str = [[NSMutableArray alloc]init];
if ([substrings containsObject:#"Category-Sequence:"])
{
NSString *index=[substrings objectAtIndex:5];
NSString *object=[substrings objectAtIndex:1];
[str insertObject:object atIndex:(index.intValue)];
}
Allocate the NSMutableArray before inserting objects into it:
NSMutableArray *strMutableArray = [[NSMutableArray alloc] init];
(You’ll also need to release it when you’re done if you’re not using ARC.)
Or you could also use a temporary object, if you don’t need to keep strMutableArray:
NSMutableArray *strMutableArray = [NSMutableArray array];
Then you can insert objects into the NSMutableArray.
Be careful with using indexes of and in different arrays, however. There might be a better way to do what you want.

Can´t add objects to mutable array which returns nil

I´m doing an app and I can´t get a mutable array to accept objects. I´v tried setting breakpoints to see what´s happening but it keeps saying that the mutable array is nil. Does anyone has an answer?
My code:
- (void)save:(id) sender {
// All the values about the product
NSString *product = self.productTextField.text;
NSString *partNumber = self.partNumberTextField.text;
NSString *price = self.priceTextField.text;
NSString *quantity = self.quantityTextField.text;
NSString *weigh = self.weighTextField.text;
NSString *file = [self filePath];
//Singleton class object
Object *newObject = [[Object alloc] init];
newObject.product = product;
newObject.partNumber = partNumber;
newObject.price = price;
newObject.quantity = quantity;
newObject.weigh = weigh;
//Array declaration
mutableArray = [[NSMutableArray alloc]initWithContentsOfFile: file];
[mutableArray addObject:newObject];
[mutableArray writeToFile:file atomically:YES];
}
While initWithContentsOfFile: can be called on an NSMutableArray, it was inherited from NSArray. The return value is an NSArray which is not mutable. If you want to add objects to your mutable array, you have to do something like this:
mutableArray = [[[NSMutableArray alloc] initWithContentsOfFile: file] mutableCopy];
[mutableArray addObject:newObject];
[mutableArray writeToFile:file atomically:YES];
Now, the addObject: call should work.
Best regards.
[NSMutableArray initWithContentsOfFile:] returns nil by default if the file can't be opened or parsed. Are you sure the file you're loading exists and is formatted correctly?
Try to check with break point on
mutableArray = [[NSMutableArray alloc]initWithContentsOfFile: file];
Line. Move your cursor on mutableArray if it shows you __NSArrayI that means it is an immutable array i.e. you cant update it and if it shows you __NSArrayM that means it is a mutable array and you can update this array.
In your case you're getting immutable array thats why you cant update it.
So you have two way to get mutable Array from this file -
Method:1
mutableArray = [[[NSMutableArray alloc] initWithContentsOfFile: file] mutableCopy];
Method:2
NSArray *anyArray = [[NSArray alloc]initWithContentsOfFile: file];
mutableArray = [[NSMutableArray alloc]initWithArray:anyArray];
In both case mutableArray woud be a mutable Array. You can update it.

NSMutableArray automatically typecasting into NSArray

I created an NSMutableArray object by
NSMutableArray *array = [[NSMutableArray alloc]init];
and used method componentsSeperatedByString: as
array = [myString componentsSeperatedByString:#"++"];
but when I performed operation on array like,
[array removeAllObjects];
I got exception like "removeAllObjects unrecognized selector send to instance".
I solved this issue by modifying code like,
NSArray *components = [myString componentsSeperatedByString:#"++"];
array = [NSMutableArray arrayWithArray:components];
and I after that could perform operation like
[array removeAllObjects];
My doubt is why did NSMutableArray automaticaqlly converted to NSArray? How Can I avoid automatic type conversion like this, to prevent exceptions? Thanks in advance....
There is a mistake in your understanding of how Objective-C works. This line:
NSMutableArray *array = [[NSMutableArray alloc]init];
allocates and initializes the array, and the pointer array points to this object. Now, this line:
array = [myString componentsSeperatedByString:#"++"];
makes the array pointer to point to the new array returned by componentsSeparatedByString method. You loose the reference to your alloced and inited mutable array when you do this, and you create the memory leak if you don't use ARC.
This is happening because [myString componentsSeperatedByString:#"++"] returns an NSArray. You can try something like this:
array = [[myString componentsSeperatedByString:#"++"] mutableCopy];
or
array = [NSMutableArray arrayWithArray:[myString componentsSeperatedByString:#"++"]];
This is because – componentsSeparatedByString: returns a NSArray: https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html#//apple_ref/occ/instm/NSString/componentsSeparatedByString:
Do something like:
array = [NSMutableArray arrayWithArray:[myString componentsSeperatedByString:#"++"]];
On the line
array = [myString componentsSeperatedByString:#"++"];
you are replacing the NSMutableArray you allocated with a new NSArray (and leaking your NSMutableArray. Try using this:
NSMutableArray *array = [NSMutableArray arrayWithArray:[myString componentsSeperatedByString:#"++"]];
It's not converted, the array pointer could be UIButton* if you write something like
array = [self likeThatButton];
where likeThatButton is your method returning UIButton*. As always in objective c, NSMutableArray *array means only the Xcode will try to analyze your code and suggest convenient warnings and code completion.
An NSMutableArray instance won't be converted automatically.
The method componentsSeperatedByString returns an NSArray-Object. You should get a compiler warning when assigning the return-value to a NSMutableArray-Pointer.

how to split string into NSMutableArray

I want to split string into NSMutableArray
I know
- (NSArray *)componentsSeparatedByString:(NSString *)separator
is available but this one is for NSArray not for NSMutableArray.
I need because after spliting i want to remove element from array by using
-(void)removeObjectAtIndex:(NSUInteger)index
which is not possible with NSArray.
Thank you
You can also just get a mutable copy of the returned array:
NSMutableArray *array = [[myString componentsSeparatedByString:#"..."] mutableCopy];
Also, remember that copy, like alloc, does allocate new memory. So when used in non-ARC code you must autorelease the copied array or manually release it when you are done with it.
Make a new NSMutableArray using
NSArray *array = [NSString componentsSeparatedByString:#"..."];
NSMutableArray *mutable = [NSMutableArray arrayWithArray:array];
Create a NSMutableArray from the output NSArray created by componentsSeparatedByString.
NSMutableArray *mutableArray = [[NSMutableArray alloc] initWithArray:array];

How to add an object to the end of an NSMutableArray

I have the following code
NSMutableArray *plistArray = [[NSMutableArray alloc] initWithContentsOfFile:filepath];
[plistArray insertObject:title atIndex:2];
but would like to rather add the object to the end of the array.
How can this be done, and do I need to set the last value to nil, at the moment I dont and it works fine.
Regards
[plistArray addObject:title];
See the NSMutableArray Class Reference.