Adding string to an array - iphone

i wanted to know how to add strings into an array.
I used the following methods but it is showing null.
1) [arrData addObject:[NSString stringWithString:strlast]];
2) [arrData addObject:strlast];
Thanks in advance

You can't add anything to an NSArray once it's created. You need to use an NSMutableArray if you want to make changes to it.
Update: You may actually have two problems.
Using an NSArray instead of an NSMutableArray when mutability is needed.
Not initializing the array object (either kind). If arrData is nil, you can happily send as many messages as you want to nil. Nothing will happen.

If it is showing null (nil) you need to make sure you set arrData somewhere in your code before trying to addObject:.
arrData = [[NSMutableArray alloc] init];
Also strlast is a string so use your second example, the first example is pointless.
[arrData addObject:strlast];

Did you allocate an array and assign it to arrData?

Try:
NSMutableArray *arrData = [NSMutableArray array];
NSString *string = #"My string";
[arrData addObject:string];
NSLog(#"%#", [arrData objectAtIndex:0]); //logs "My string"

If you're using a non-mutable array, you can also use arrayByAddingObject:
arrData = [arrData arrayByAddingObject: strlast];
but a mutable array is probably a better idea.

Related

iOS NSMutabledictionary is null when I setValue and forKey

I know I may been doing something very stupid but I can not figure out where is the error on this code:
NSString *string=#"some string";
[self.dataResponse setValue:string forKey:#"Code"];
Also I tried:
NSString *string=#"some string";
[self.dataResponse setObject:string forKey:#"Code"];
but in both cases my nsmutable dictionary self.dataResponse is null. Any of you knows what I'm doing wrong?
I really appreciate your help.
You need to Alloc and Init the NSMutableArray to set values in it. Example:
self.dataResponse = [[NSMutableArray alloc] init]; // This is alloc and init
NSString *string = #"Some Val";
[self.dataResponse setValue:string forKey:#"Code"];
your variable self.dataResponse is just nil.
You have to say
self.dataResponse = [NSMutableDictionary new];
to allocate and instantiate a dictionary.
afterwards you can assign values to the keys!
I think you must not have initialised your mutable dictionary yet, wether using alloc/init or a convenience initialiser. Until you do that, setting any object for key will do nothing. You can do this lazily or in view did load (amongst other places).

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.

iPhone:Got warning when reverse a NSMutablearray

I need reverse(sort in descending order) a NSMutablearray.I tried the following code and it works,but got a warning. How could I remove the warning?
NSMutablearray *resStatusArray;
[resStatusArray sortUsingSelector:#selector(compare:)];
resStatusArray=[[resStatusArray reverseObjectEnumerator] allObjects];
Warning:Incompitable pointer types assigning to 'NSMutablearray*_strong' from ' NSarray *'
user1118321 is correct in the explanation. To fix it, you would create a new mutable array. I suspect this is safer than a cast.
resStatusArray = [NSMutableArray arrayWithArray:[[resStatusArray reverseObjectEnumerator] allObjects]];
The allObjects method returns an NSArray*, not an NSMutableArray*, so the compiler is telling you that your assignment to an NSMutableArray* variable is incorrect.
If your are sure what your are doing, you can use a cast:
resStatusArray=(NSMutableArray*_strong)[[resStatusArray reverseObjectEnumerator] allObjects];
However, I doubt that this is semantically correct.
Set it to be equal to:
[NSMutableArray arrayWithArray:[[arrayNameToReverse reverseObjectEnumerator] allObjects]];
This is essentially creating a new array, from the old mutable array, but reversed. The reason it works is because NSMutableArray is a subclass of NSArray. So, your code to reverse your array would be:
resStatusArray = [NSMutableArray arrayWithArray:[[resStatusArray reverseObjectEnumerator] allObjects]];

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.

NSMutableArray not retaining the value even after setting the property

In my iphone app i have implemented the SearchBar on TableView.
Now the SearchBar Searches the items but the searched items are not shown in the tableview as the NSMutableArray which fills up the table with the search results is not retaining the values.
I have put the screenshot of the code and the NSLog statements for the count of copyListOfItems always return 0 even though the NSLog(#"%#",sTemp); shows the searched items in Console.
I have created the property for the NSMutableArray copyListOfItems and also synthesized it but its count in the Console is always shown as Zero.
Here is the Code:
searchArray = [Food mutableCopy];
for (NSString *sTemp in searchArray)
{
NSLog(#"Value: %#",NSStringFromClass([sTemp class]));
NSRange titleResultsRange = [sTemp rangeOfString:searchText options:NSCaseInsensitiveSearch];
if (titleResultsRange.length > 0)
{
NSLog(#"sTemp is:%#",sTemp);
NSLog(#" is:%#",sTemp);
[copyListOfItems addObject:sTemp];
[copyListOfItems retain];
}
NSLog(#"Copy list count in Search Delegate Method inside For : %d",[copyListOfItems count]);
}
NSLog(#"Copy list count in Search Delegate Method : %d",[copyListOfItems count]);
[searchArray release];
searchArray = nil;
searching = YES;
[self.table reloadData];
de:
What should I do?
Please Help
Please Suggest
Thanks
From what you've said, it sounds as though the copyListOfItems array is never created. Synthesizing the property creates a pair of accessor methods, but doesn't automatically create an instance of NSMutableArray for you.
So somewhere, you'll need to call [[NSMutableArray alloc] init] (or some variant of init...), and assign the result to the instance variable, or call [NSMutableArray array] (or a variant of array...), and pass the result as an argument to the setCopyListOfItems: method.
I can only assume that you're over-releasing the items in the array. It appears that you do not have a good grip on the retain/release concept, since you're over-retaining the NSArray copyListOfItems. You shouldn't be calling -retain on the same object within a loop since you're incrementing a single object's retain count by 1 for each iteration of the loop.
That aside, what does this code output in its NSLog() calls? It doesn't make a lot of sense. Why do you try to take a mutable copy of (what appears to be) a class called Food?
What exactly is "Food"? An objective-C object, or an objective-C class? This should not be compiling at all in my opinion, unless it's just very badly named.
Make sure you always alloc init the NSMutableArray. If you don't do that, all the items you add will just euhm.. disappear. So make sure you do this somewhere:
searchArray = [[NSMutableArray alloc] init];
Oops..!!!! Cleaned my project and build and run again and it has started working.Thanks guys for being so helpful.. :]
where are you creating the copyListOfItems Array?
I guess copyListOfItems is nil. And you are trying to add something to nil array and trying to retain the nil.
Note: whatever the operation you do on the nil will not be affected. Check whether you are creating the copyListOfItems array properly.
And why are you trying to retain the same array after adding each object?